关于React源码中一些全局变量用意有些疑问,贴了关于 isRendering 全局变量的代码,有没有帮忙解答一下的?

如题,比如 ReactFilberScheduler.js  中有一个全局变量 isRendering 变量在 requestWork  和 performWorkOnRoot 方法中有用到,

requestWork 函数开头判断当 isRendering = true 的直接返回return;而在 performWorkOnRoot 的开头将 isRendering 置为 true  而在末尾置为 false,那么问题来了  requestWork  的开头对 isRendering 的判断有什么意义?

function requestWork(root: FiberRoot, expirationTime: ExpirationTime) {

  addRootToSchedule(root, expirationTime);

  if (isRendering) {

    // Prevent reentrancy. Remaining work will be scheduled at the end of

    // the currently rendering batch.

    return;

  }

  //....Omitted code

}

function performWorkOnRoot(root: FiberRoot, expirationTime: ExpirationTime, isExpired: boolean) {

  invariant(

    !isRendering,

    'performWorkOnRoot was called recursively. This error is likely caused ' +

      'by a bug in React. Please file an issue.',

  );


  isRendering = true;

  //...Omitted code


  isRendering = false;

}


一身三影
浏览 1415回答 3
3回答

pardon110

很显然只是个标志位,控制代码执行流程,在一些异步执行需要同步代码的情况下用到。你需要知道,代码并不总是从上到下逐行执行,而异步执行在js中是常态
打开App,查看更多内容
随时随地看视频慕课网APP