面试官:react中的setState是同步的还是异步的
hello,这里是潇晨,大家在面试的过程是不是经常会遇到这样的问题,react的setState是同步的还是异步的,这个问题回答的时候一定要完整,来看下面这几个例子:
例子1:点击button触发更新,在handle函数中会调用两次setState
export default class App extends React.Component {
state = {
num: 0,
};
updateNum = () => {
console.log("before", this.state.num);
this.setState({ num: this.state.num + 1 });
this.setState({ num: this.state.num + 1 });
console.log("after", this.state.num);
};
render() {
const { num } = this.state;
console.log("render", num);
return <button onClick={this.updateNum}>hello {num}</button>;
}
}
//打印结果
//render 0
//before 0
//after 0
//render 1
例子2:例子1的两次setState在setTimeout回调中执行
export default class App extends React.Component {
state = {
num: 0,
};
updateNum = () => {
console.log("before", this.state.num);
setTimeout(() => {
this.setState({ num: this.state.num + 1 });
this.setState({ num: this.state.num + 1 });
console.log("after", this.state.num);
}, 0);
};
render() {
const { num } = this.state;
console.log("render", num);
return <button onClick={this.updateNum}>hello {num}</button>;
}
}
//打印结果
//render 0
//before 0
//render 1
//render 2
//after 2
例子3:用unstable_batchedUpdates在setTimout中执行,unstable_batchedUpdates的回调函数中调用两次setState
import { unstable_batchedUpdates } from "react-dom";
export default class App extends React.Component {
state = {
num: 0,
};
updateNum = () => {
console.log("before", this.state.num);
setTimeout(() => {
unstable_batchedUpdates(()=>{
this.setState({ num: this.state.num + 1 });
this.setState({ num: this.state.num + 1 });
console.log("after", this.state.num);
})
}, 0);
};
render() {
const { num } = this.state;
console.log("render", num);
return <button onClick={this.updateNum}>hello {num}</button>;
}
}
//打印结果
//render 0
//before 0
//after 0
//render 1
例子4:两次setState在setTimeout回调中执行,但是用concurrent模式启动,也就是调用ReactDOM.unstable_createRoot启动应用。
import React from "react";
import ReactDOM from "react-dom";
export default class App extends React.Component {
state = {
num: 0,
};
updateNum = () => {
console.log("before", this.state.num);
setTimeout(() => {
this.setState({ num: this.state.num + 1 });
this.setState({ num: this.state.num + 1 });
console.log("after", this.state.num);
}, 0);
};
render() {
const { num } = this.state;
console.log("render", num);
return <button onClick={this.updateNum}>hello {num}</button>;
}
}
ReactDOM.unstable_createRoot(rootEl).render(<App />);
//打印结果
//render 0
//before 0
//after 0
//render 1
batchedUpdates
简单来说,在一个上下文中同时触发多次更新,这些更新会合并成一次更新,例如
onClick() {
this.setState({ count: this.state.count + 1 });
this.setState({ count: this.state.count + 1 });
}
在之前的react版本中如果脱离当前的上下文就不会被合并,例如把多次更新放在setTimeout中,原因是处于同一个context的多次setState的executionContext都会包含BatchedContext,包含BatchedContext的setState会合并,当executionContext等于NoContext,就会同步执行SyncCallbackQueue中的任务,所以setTimeout中的多次setState不会合并,而且会同步执行。
onClick() {
setTimeout(() => {
this.setState({ count: this.state.count + 1 });
this.setState({ count: this.state.count + 1 });
});
}
export function batchedUpdates<A, R>(fn: A => R, a: A): R {
const prevExecutionContext = executionContext;
executionContext |= BatchedContext;
try {
return fn(a);
} finally {
executionContext = prevExecutionContext;
if (executionContext === NoContext) {
resetRenderTimer();
//executionContext为NoContext就同步执行SyncCallbackQueue中的任务
flushSyncCallbackQueue();
}
}
}
在Concurrent mode下,上面的例子也会合并为一次更新,根本原因在如下一段简化的源码,如果多次setState,会比较这几次setState回调的优先级,如果优先级一致,则先return掉,不会进行后面的render阶段
function ensureRootIsScheduled(root: FiberRoot, currentTime: number) {
const existingCallbackNode = root.callbackNode;//之前已经调用过的setState的回调
//...
if (existingCallbackNode !== null) {
const existingCallbackPriority = root.callbackPriority;
//新的setState的回调和之前setState的回调优先级相等 则进入batchedUpdate的逻辑
if (existingCallbackPriority === newCallbackPriority) {
return;
}
cancelCallback(existingCallbackNode);
}
//调度render阶段的起点
newCallbackNode = scheduleCallback(
schedulerPriorityLevel,
performConcurrentWorkOnRoot.bind(null, root),
);
//...
}
那为什么在Concurrent mode下,在setTimeout回调多次setState优先级一致呢,因为在获取Lane的函数requestUpdateLane,只有第一次setState满足currentEventWipLanes === NoLanes,所以他们的currentEventWipLanes参数相同,而在findUpdateLane中schedulerLanePriority参数也相同(调度的优先级相同),所以返回的lane相同。
export function requestUpdateLane(fiber: Fiber): Lane {
//...
if (currentEventWipLanes === NoLanes) {//第一次setState满足currentEventWipLanes === NoLanes
currentEventWipLanes = workInProgressRootIncludedLanes;
}
//...
//在setTimeout中schedulerLanePriority, currentEventWipLanes都相同,所以返回的lane也相同
lane = findUpdateLane(schedulerLanePriority, currentEventWipLanes);
//...
return lane;
}
总结:
legacy模式下:命中batchedUpdates时是异步 未命中batchedUpdates时是同步的
concurrent模式下:都是异步的