React源码解析(三) —— 应用启动过程

这里以React18的 Concurrent 并发模式作为基础

js 复制代码
ReactDOM.createRoot(rootNode).render(<App />)

createRoot被调用时发生了什么?

通过观察如下调用堆栈我们可以看到具体的过程:

执行的顺序从createRoot函数开始:

js 复制代码
export function createRoot(
  container: Element | Document | DocumentFragment,
  options?: CreateRootOptions,
): RootType {
 
  // 省略掉一些处理createRoot options的逻辑
  
  const root = createContainer(
    container,
    ConcurrentRoot,
    null,
    isStrictMode,
    concurrentUpdatesByDefaultOverride,
    identifierPrefix,
    onUncaughtError,
    onCaughtError,
    onRecoverableError,
    transitionCallbacks,
  );
  return new ReactDOMRoot(root);
}

可以看到在createRoot中会调用createContainer函数

js 复制代码
function createContainer(containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) {
  var hydrate = false;
  var initialChildren = null;
  return createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
}

在createContainer函数 中会调用createFiberRoot

js 复制代码
function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, 
identifierPrefix, onRecoverableError, transitionCallbacks) {
  var root = new FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError);
  var uninitializedFiber = createHostRootFiber(tag, isStrictMode);
  root.current = uninitializedFiber;
  uninitializedFiber.stateNode = root;
  {
    var _initialState = {
      element: initialChildren,
      isDehydrated: hydrate,
      cache: null,
      // not enabled yet
      transitions: null,
      pendingSuspenseBoundaries: null
    };
    uninitializedFiber.memoizedState = _initialState;
  }

  initializeUpdateQueue(uninitializedFiber);
  return root;
}

在createFiberRoot中会有如下过程

  • 创建一个 FiberRootNode 的实例 FiberRoot作为整个React应用的根节点
  • 调用 createHostRootFiber 创建 一个尚未初始化的Fiber树
  • 将 FiberRoot.current 设置为 HostRootFiber 将 HostRootFiber 的 stateNode 设置为 FiberRoot在二者之间建立联系
  • 使用initializeUpdateQueue初始化更新队列
  • 返回根节点

ps:更新队列是一个内部的数据结构,用于管理组件的状态更新和上下文变化。它负责跟踪组件的更新,并将它们排队以便在合适的时机批量处理。

root.render()

上一步中createRoot创建的root对象prototype上的方法被调用:

js 复制代码
ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render =
  function (children: ReactNodeList): void {
    const root = this._internalRoot;
    updateContainer(children, root, null, null);
  };

进入updateContainer,updateContainer中处理了lane优先级相关信息,调用了updateContainerImpl进行后续处理,updateContainer相当于ReactDOM和reconciler的桥梁。

js 复制代码
export function updateContainer(
  element: ReactNodeList,
  container: OpaqueRoot,
  parentComponent: ?React$Component<any, any>,
  callback: ?Function,
): Lane {
  const current = container.current;
  const lane = requestUpdateLane(current);
  updateContainerImpl(
    current,
    lane,
    element,
    container,
    parentComponent,
    callback,
  );
  return lane;
}

updateContainerImpl:

  • 调用 enqueueUpdate 函数将更新对象到根 Fiber 节点(rootFiber)上,并指定更新的优先级车道(lane)
  • 调用 scheduleUpdateOnFiber 函数将更新调度到根 Fiber 节点上,这将触发协调算法(reconciliation)
js 复制代码
function updateContainerImpl(
  rootFiber: Fiber,
  lane: Lane,
  element: ReactNodeList,
  container: OpaqueRoot,
  parentComponent: ?React$Component<any, any>,
  callback: ?Function,
): void {

  if (enableSchedulingProfiler) {
    markRenderScheduled(lane);
  }

  const context = getContextForSubtree(parentComponent);
  if (container.context === null) {
    container.context = context;
  } else {
    container.pendingContext = context;
  }


  const update = createUpdate(lane);
  update.payload = {element};

  callback = callback === undefined ? null : callback;
  
  if (callback !== null) {
    update.callback = callback;
  }

  const root = enqueueUpdate(rootFiber, update, lane);
  
  if (root !== null) {
    startUpdateTimerByLane(lane);
    // 进入reconciler
    scheduleUpdateOnFiber(root, rootFiber, lane);
    entangleTransitions(root, rootFiber, lane);
  }
}

调用之后会进入调度以及协调的过程,相关内容在后续的文章中更新;

总结

本文解释了React应用启动入口ReactDOM.createRoot和root.render()方法的内部执行过程。

相关推荐
Thanks_ks2 小时前
JavaScript 事件循环机制详解:同步任务、微任务与宏任务的执行顺序
javascript·promise·前端面试·async/await·事件循环·宏任务·微任务
ZhengEnCi4 小时前
前端日志和后端日志怎么记:分级、JSON 格式、按天分文件与保留策略
前端·后端·python
kyriewen5 小时前
我给 61 个前端库排了两次名,最多差了 46 位
前端·javascript·程序员
亲亲小宝宝鸭6 小时前
Cesium启动:TLE数据是如何变成轨迹线的
前端·cesium
阿里云云原生6 小时前
对话即构建,在 AgentCore 构建 Agent 就是这么简单
前端·agent
夕水7 小时前
我给我的诗写了个后台,顺手写了 一个组件库ew-solid-ui
前端·javascript·typescript
KevinWang_7 小时前
iOS 开发计划(五) - 做一个离线音乐播放器
javascript
狗头大军之江苏分军8 小时前
前端转行干能干什么?我转行试了下(被迫)
前端·后端
孟陬8 小时前
Foobar 技术周刊#2:约会已死?用户急剧下滑,约会App大概率会弱化约会属性转向轻陪伴。我有个建议:
前端·后端·rust
parade岁月8 小时前
VTable Guild 3.0.0 发布,面向 Vue 3 的 ProTable 式业务表格
前端