关于react.js:面试官react中的setState是同步的还是异步的

8次阅读

共计 4470 个字符,预计需要花费 12 分钟才能阅读完成。

面试官: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. 总结 & 第一章的面试题解答

正文完
 0