面试官: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 模式下:都是异步的
视频讲解(高效学习):点击学习
往期 react 源码解析文章:
1.开篇介绍和面试题
2.react的设计理念
3.react源码架构
4.源码目录结构和调试
5.jsx&核心api
6.legacy和concurrent模式入口函数
7.Fiber架构
8.render阶段
9.diff算法
10.commit阶段
11.生命周期
12.状态更新流程
13.hooks源码
14.手写hooks
15.scheduler&Lane
16.concurrent模式
17.context
18事件系统
19.手写迷你版react
20.总结&第一章的面试题解答
评论