面试官:react中的setState是同步的还是异步的_2023-02-19
2023-03-07 09:45:47 时间
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模式下:都是异步的
相关文章
- 抽烟行为监测识别系统
- ebpf内核态开发环境搭建
- 同宿主机暴露多个docker容器IP
- ebfp内核态开发经验总结
- 容器网络参考
- 将chatGPT与传统搜索引擎结合——创建新一代的搜索引擎
- 特斯拉的碳积分交易:10年狂赚54亿美元
- 质量部天天念叨的“FMEA”是什么呀
- 委派模式——从SLF4J说起
- 进行PFMEA应考虑的因素有哪些?
- 政府企业网络设备如何实时监控?-华汇数据IT运维监控平台
- R与RStudio 20230130
- 如何进行生产现场管理和改善
- 【好玩儿的Docker项目】Pingvin Share——一个专注于文件分享的高颜值轻量小工具!
- 移动端样式问题汇总
- Linux音频采集和在国产化平台中遇到的坑(一)
- 快速可靠的包管理工具 Yarn
- GitHub 2019 年度报告解读:开源生态和技术趋势
- ES6新增特性
- Vue.js中 watch 的使用方法