react 16.8.6版本源码中unbatchedUpdates实现原理?

export function unbatchedUpdates<A, R>(fn: (a: A) => R, a: A): R {
  const prevExecutionContext = executionContext;
  executionContext &= ~BatchedContext;
  executionContext |= LegacyUnbatchedContext;
  try {
    return fn(a);
  } finally {
    executionContext = prevExecutionContext;
    if (executionContext === NoContext) {
      // Flush the immediate callbacks that were scheduled during this batch
      flushSyncCallbackQueue();
    }
  }
}

请问unbatchedUpdates中的这段代码起了什么作用?

const prevExecutionContext = executionContext;
  executionContext &= ~BatchedContext;
  executionContext |= LegacyUnbatchedContext;
阅读 4.1k
3 个回答

在将upbatchedUpdates前,我们看一下一些常量和变量

const NoContext = /*                    */ 0b000000;
const BatchedContext = /*               */ 0b000001;
const EventContext = /*                 */ 0b000010;
const DiscreteEventContext = /*         */ 0b000100;
const LegacyUnbatchedContext = /*       */ 0b001000;
const RenderContext = /*                */ 0b010000;
const CommitContext = /*                */ 0b100000;

// 描述当前的执行栈
// Describes where we are in the React execution stack
let executionContext: ExecutionContext = NoContext;

上面的一些常量都是定义的React中对应的执行栈。变量executionContext则记录当前的执行栈.

现在,我们回到upbatchedUpdates方法中

export function unbatchedUpdates<A, R>(fn: (a: A) => R, a: A): R {
  // 暂存当前执行栈
  const prevExecutionContext = executionContext;、
  // 更改执行栈
  executionContext &= ~BatchedContext;
  executionContext |= LegacyUnbatchedContext;
  // 最后通过 "|=" 将当前的执行栈更改为 "LegacyUnbatchedContext"
  try {
    // 回调就是updateContainer
    return fn(a);
  } finally {
    // 在执行完回调之后,会恢复执行栈
    executionContext = prevExecutionContext;
    if (executionContext === NoContext) {
      // Flush the immediate callbacks that were scheduled during this batch
      flushSyncCallbackQueue();
    }
  }
}
新手上路,请多包涵

将当前执行环境设置成LegacyUnbatchedContext

新手上路,请多包涵
const BatchedContext = /*               */ 0b000001;
const LegacyUnbatchedContext = /*       */ 0b001000;

这段是个位运算,就是把prevExecutionContextBatchedContext位置0,然后把LegacyUnbatchedContext的位置1。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏