ReactDom.render分析

1.步骤

1.建立ReactRoot

2.建立FiberRoot和FiberRoot

3.建立更新

2. render方法:

render(
    element: React$Element<any>,
    container: DOMContainer,
    callback: ?Function,
  ) {
    invariant(
      isValidContainer(container),
      'Target container is not a DOM element.',
    );
    return legacyRenderSubtreeIntoContainer(
      null,
      element,
      container,
      false,
      callback,
    );
  },

render方法能够传入三个参数包括ReactElement、DOM的包裹节点,和渲染结束后执行的回调方法。
而后验证invariant验证container是不是有效的Dom节点。
最后返回legacyRenderSubtreeIntoContainer方法执行后的结果,再来看看这个方法的参数react

function legacyRenderSubtreeIntoContainer(
  parentComponent: ?React$Component<any, any>,
  children: ReactNodeList,
  container: DOMContainer,
  forceHydrate: boolean,
  callback: ?Function,
)
这里传入五个参数,第一个是parentComponent不存在传入null,第二个是传入container的子元素,第三个是建立ReactRoot的包裹元素,第四个是协调更新的选项,第五个是渲染后的回调方法。
let root: Root = (container._reactRootContainer: any);
  if (!root) {
    // Initial mount
    root = container._reactRootContainer = legacyCreateRootFromDOMContainer(
      container,
      forceHydrate,
    );
先检验ReactRoot是否存在不存在则执行传入container,
forceHydrate后的 legacyCreateRootFromDOMContainer函数建立一个ReactRoot。forceHydrate在render方法中传入的false,在Hydrate方法中传入的true,主要是为了区分服务端渲染和客户端渲染,true时未复用原来的节点适合服务端渲染,
若是是false则执行 container.removeChild(rootSibling)删除全部的子节点。
而后返回经过 new ReactRoot(container, isConcurrent, shouldHydrate)
function ReactRoot(
  container: DOMContainer,
  isConcurrent: boolean,
  hydrate: boolean,
) {
  const root = createContainer(container, isConcurrent, hydrate);
  this._internalRoot = root;
}

在这个方法中调用createContainer建立root,这个方法从react-reconciler/inline.dom文件中引入:算法

export function createContainer(
  containerInfo: Container,
  isConcurrent: boolean,
  hydrate: boolean,
): OpaqueRoot {
  return createFiberRoot(containerInfo, isConcurrent, hydrate);
}

在这个方法中又调用了createFiberRoot方法建立FiberRoot
在建立玩root后执行unbatchedUpdates更新,传入root。render方法更新:dom

unbatchedUpdates(() => {
      if (parentComponent != null) {
        root.legacy_renderSubtreeIntoContainer(
          parentComponent,
          children,
          callback,
        );
      } else {
        root.render(children, callback);
      }
    });

执行updateContainer(children, root, null, work._onCommit);方法,这个方法最终调用enqueueUpdatescheduleWork,并返回expireTime,这些进行调度算法和进行优先级判断函数

相关文章
相关标签/搜索