当前位置:首页 > 科技  > 软件

一图看懂 React 源码中的同步更新逻辑

来源: 责编: 时间:2024-05-11 09:21:16 377观看
导读在 React 源码中,scheduleUpdateOnFiber 是所有任务的唯一入口方法。我们前面分析 useState 的实现原理章节中,我们可以清晰的知道,当我们调用 dispatchSetState 时,最终会调用该入口方法。scheduleUpdateOnFiber 主要用

RKz28资讯网——每日最新资讯28at.com

在 React 源码中,scheduleUpdateOnFiber 是所有任务的唯一入口方法。我们前面分析 useState 的实现原理章节中,我们可以清晰的知道,当我们调用 dispatchSetState 时,最终会调用该入口方法。RKz28资讯网——每日最新资讯28at.com

RKz28资讯网——每日最新资讯28at.com

scheduleUpdateOnFiber 主要用于触发一个 Fiber 节点上的调度更新任务,该函数里主要有两个核心逻辑。RKz28资讯网——每日最新资讯28at.com

// Mark that the root has a pending update.// 标记 root 上有一个更新任务markRootUpdated(root, lane, eventTime);ensureRootIsScheduled(root, eventTime);

markRootUpdated 的逻辑如下,简单了解一下即可。RKz28资讯网——每日最新资讯28at.com

export function markRootUpdated(  root: FiberRoot,  updateLane: Lane,  eventTime: number,) {  // 设置本次更新的优先级  root.pendingLanes |= updateLane;  // 重置 root 应用根节点的优先级  if (updateLane !== IdleLane) {      // 由 Suspence 而挂起的 update 对应的 lane 集合    root.suspendedLanes = NoLanes;     // 由请求成功,Suspence 取消挂起的 update 对应的 Lane 集合    root.pingedLanes = NoLanes;   }  const eventTimes = root.eventTimes;  const index = laneToIndex(updateLane);  eventTimes[index] = eventTime;}

ensureRootIsScheduled 的主要目的要确保 root 根节点被调度。在该逻辑中,会根据 root.pendingLanes 信息计算出本次更新的 Lanes: nextLanes。RKz28资讯网——每日最新资讯28at.com

const nextLanes = getNextLanes(  root,  root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes,);

然后根据 nextLanes 计算出本批次集合中优先级最高的 Lane,作为本地任务的优先级。RKz28资讯网——每日最新资讯28at.com

// We use the highest priority lane to represent the priority of the callback.const newCallbackPriority = getHighestPriorityLane(nextLanes);

后续的逻辑就是取出当前已存在的调度优先级,与 newCallbackPriority 进行对比,根据对比结果来执行不同的更新方法。当该值等于 SyncLane 时,表示为同步更新。RKz28资讯网——每日最新资讯28at.com

同步优先级例如点击事件。RKz28资讯网——每日最新资讯28at.com

然后会判断是否支持微任务更新,如果不支持最后会执行 scheduleCallback。RKz28资讯网——每日最新资讯28at.com

if (newCallbackPriority === SyncLane) {  if (supportsMicrotasks) {    // Flush the queue in a microtask.    if (__DEV__ && ReactCurrentActQueue.current !== null) {      // Inside `act`, use our internal `act` queue so that these get flushed      // at the end of the current scope even when using the sync version      // of `act`.      ReactCurrentActQueue.current.push(flushSyncCallbacks);    } else {      scheduleMicrotask(() => {        // In Safari, appending an iframe forces microtasks to run.        // https://github.com/facebook/react/issues/22459        // We don't support running callbacks in the middle of render        // or commit so we need to check against that.        if (          (executionContext & (RenderContext | CommitContext)) ===          NoContext        ) {          // Note that this would still prematurely flush the callbacks          // if this happens outside render or commit phase (e.g. in an event).          flushSyncCallbacks();        }      });    }  } else {    // Flush the queue in an Immediate task.    scheduleCallback(ImmediateSchedulerPriority, flushSyncCallbacks);  }}

scheduleSyncCallback 的逻辑,也就是同步任务的调度非常简单,就是将执行同步任务的回调添加到一个同步队列 syncQueue 中。RKz28资讯网——每日最新资讯28at.com

export function scheduleSyncCallback(callback: SchedulerCallback) {  // Push this callback into an internal queue. We'll flush these either in  // the next tick, or earlier if something calls `flushSyncCallbackQueue`.  if (syncQueue === null) {    syncQueue = [callback];  } else {    // Push onto existing queue. Don't need to schedule a callback because    // we already scheduled one when we created the queue.    syncQueue.push(callback);  }}

这里的 callback 是之前传入的 performSyncWorkOnRoot,这是用来执行同步更新任务的方法。他的逻辑主要包括:RKz28资讯网——每日最新资讯28at.com

  • 调用 renderRootSync,该方法会执行 workLoopSync,最后生成 Fiber true。
  • 将创建完成的 Fiber tree 挂载到 root 节点上。
  • 最后调用 commitRoot,进入 commit 阶段修改真实 DOM。
function performSyncWorkOnRoot(root) {  ...  let exitStatus = renderRootSync(root, lanes);    ...  root.finishedWork = finishedWork;  root.finishedLanes = lanes;  commitRoot(    root,    workInProgressRootRecoverableErrors,    workInProgressTransitions,  );  ensureRootIsScheduled(root, now());  return null;}

workLoopSync 的逻辑也非常简单,如下:RKz28资讯网——每日最新资讯28at.com

function workLoopSync() {  // Already timed out, so perform work without checking if we need to yield.  while (workInProgress !== null) {    performUnitOfWork(workInProgress);  }}

在 performUnitOfWork 中,会调用 beginWork 方法开始创建 Fiber 节点。RKz28资讯网——每日最新资讯28at.com

var next = beginWork(  current,   unitOfWork,   subtreeRenderLanes);

总结

同步更新的过程比较简单,从 scheduleUpdateOnFiber 到 beginWork 这中间的流程里,大多数逻辑都在进行各种不同情况的判断,因此源码看上去比较吃力,实际逻辑并不是很重要,简单了解即可,重要的是 beginWork 创建 Fiber 节点的方法,这跟我们之前文章里提到过的优化策略是一致的。RKz28资讯网——每日最新资讯28at.com

本文链接:http://www.28at.com/showinfo-26-87990-0.html一图看懂 React 源码中的同步更新逻辑

声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。邮件:2376512515@qq.com

上一篇: 一篇学会Go中reflect反射的详细用法

下一篇: SpringBoot3使用虚拟线程一定要小心了

标签:
  • 热门焦点
  • MIX Fold3包装盒泄露 新机本月登场

    小米的全新折叠屏旗舰MIX Fold3将于本月发布,近日该机的真机包装盒在网上泄露。从图上来看,新的MIX Fold3包装盒在外观设计方面延续了之前的方案,变化不大,这也是目前小米旗舰
  • 企业采用CRM系统的11个好处

    客户关系管理(CRM)软件可以为企业提供很多的好处,从客户保留到提高生产力。  CRM软件用于企业收集客户互动,以改善客户体验和满意度。  CRM软件市场规模如今超过580
  • Flowable工作流引擎的科普与实践

    一.引言当我们在日常工作和业务中需要进行各种审批流程时,可能会面临一系列技术和业务上的挑战。手动处理这些审批流程可能会导致开发成本的增加以及业务复杂度的上升。在这
  • 让我们一起聊聊文件的操作

    文件【1】文件是什么?文件是保存数据的地方,是数据源的一种,比如大家经常使用的word文档、txt文件、excel文件、jpg文件...都是文件。文件最主要的作用就是保存数据,它既可以保
  • 2023年,我眼中的字节跳动

    此时此刻(2023年7月),字节跳动从未上市,也从未公布过任何官方的上市计划;但是这并不妨碍它成为中国最受关注的互联网公司之一。从2016-17年的抖音强势崛起,到2018年的“头腾
  • OPPO、vivo、小米等国内厂商Q2在印度智能手机市场份额依旧高达55%

    7月20日消息,据外媒报道,研究机构的报告显示,在全球智能手机出货量同比仍在下滑的大背景下,印度这一有潜力的市场也未能幸免,出货量同比也有下滑,多家厂
  • 疑似小米14外观设计图曝光:后置相机模组变化不大

    下半年的大幕已经开启,而谁将成为下半年手机圈的主角就成为了大家关注的焦点,其中被传有望拿下新一代骁龙8 Gen3旗舰芯片的小米14系列更是备受大家瞩
  • OPPO K11搭载高性能石墨散热系统:旗舰同款 性能凉爽释放

    日前OPPO官方宣布,将于7月25日14:30举办新品发布会,届时全新的OPPO K11将正式与大家见面,将主打旗舰影像,和同档位竞品相比,其最大的卖点就是将配备索尼
  • DRAM存储器10月价格下跌,NAND闪存本月价格与上月持平

    10月30日,据韩国媒体消息,自今年年初以来一直在上涨的 DRAM 存储器的交易价格仅在本月就下跌了近 10%,此次是全年首次降价,而NAND 闪存本月价格与上月持平。市
Top