React源碼學習(四):渲染入口:ReactDOM.render

一、源碼學習

1. ReactDOM.render 對外暴露代碼位于源文件:

// react-dom/src/client/ReactDOM.js
import {
  ......
  render,
  ......
} from './ReactDOMLegacy';

export {
   ......
  findDOMNode,
  hydrate,
  render,
  unmountComponentAtNode,
  ......
};

2. 查看最原始的ReactDOM.reader方法,發(fā)現其支持3個參數:

  • element(來自React.createElement創(chuàng)建的VDOM)
  • container(H5根節(jié)點)
  • callback(可選)
// react-dom/src/client/ReactDOMLegacy.js
export function render(
  element: React$Element<any>,
  container: Container,
  callback: ?Function,
) {
  ......
  return legacyRenderSubtreeIntoContainer(
     null,
     element,
    container,
    false,
    callback,
  );
}

3. 繼續(xù)查看legacyRenderSubtreeIntoContainer:

function legacyRenderSubtreeIntoContainer(
  parentComponent: ?React$Component<any, any>,
  children: ReactNodeList,
  container: Container,
  forceHydrate: boolean,
  callback: ?Function,
) {
   ......

  let root: RootType = (container._reactRootContainer: any);
  let fiberRoot;
  if (!root) {
    // Initial mount
    root = container._reactRootContainer = legacyCreateRootFromDOMContainer(
      container,
      forceHydrate,
    );
    fiberRoot = root._internalRoot;
    if (typeof callback === 'function') {
      const originalCallback = callback;
      callback = function() {
        const instance = getPublicRootInstance(fiberRoot);
        originalCallback.call(instance);
      };
    }
    // Initial mount should not be batched.
    unbatchedUpdates(() => {
      updateContainer(children, fiberRoot, parentComponent, callback);
    });
  } else {
    ......
    // Update
    updateContainer(children, fiberRoot, parentComponent, callback);
  }
  return getPublicRootInstance(fiberRoot);
}

源碼中,if-else中 fiberRoot這段是IF和ELSE中是一樣的,只是最后的更新方式不一樣。

該方法判斷是否是首次初始化(判斷root是否存在):

  • 不存在則先創(chuàng)建root = legacyCreateRootFromDOMContainer,然后 updateContainer;
  • 存在則直接 updateContainer;

4. 我們來查看是如何創(chuàng)建root的:

  • 清空container所有內容;
  • 創(chuàng)建root;
function legacyCreateRootFromDOMContainer(
  container: Container,
  forceHydrate: boolean, // 調用render時該參數為false
): RootType {
  // shouldHydrate = false
  const shouldHydrate =
    forceHydrate || shouldHydrateDueToLegacyHeuristic(container);

    // 清空container所有內容
  if (!shouldHydrate) {
    let warned = false;
    let rootSibling;
    while ((rootSibling = container.lastChild)) {
      container.removeChild(rootSibling);
    }
  }

  return createLegacyRoot(
    container,
    shouldHydrate ? {hydrate: true}: undefined
  );
}
// react-dom/src/client/ReactDOMRoot.js
export function createLegacyRoot(
  container: Container,
  options?: RootOptions,
): RootType {
  // LegacyRoot = 0
  return new ReactDOMBlockingRoot(container, LegacyRoot, options);
}

function ReactDOMBlockingRoot(
  container: Container,
  tag: RootTag,
  options: void | RootOptions,
) {
  this._internalRoot = createRootImpl(container, tag, options);
}

function createRootImpl(
  container: Container,
  tag: RootTag,
  options: void | RootOptions, // undefined
) {
  ......
  // 重點
  const root = createContainer(container, tag, false, null);
  markContainerAsRoot(root.current, container);
  ......
  return root;
}

方法 createRootImpl 中的兩個重點調用:

  • createContainer;
  • markContainerAsRoot;(之后會在【legacyRenderSubtreeIntoContainer】中判斷root是否已經初始化過)

5. 繼續(xù)查看如何創(chuàng)建 root 的:

// react-reconciler/src/ReactFiberReconciler.js
export function createContainer(
  containerInfo: Container,
  tag: RootTag,
  hydrate: boolean,
  hydrationCallbacks: null | SuspenseHydrationCallbacks,
): OpaqueRoot {
  return createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks);
}

6. createFiberRoot干了4件事:

創(chuàng)建root,類型是 FiberRootNode;

  • 創(chuàng)建 Fiber;
  • 初始化更新隊列;
  • 返回創(chuàng)建好的 root ;
// react-reconciler/src/ReactFiberRoot.js
export function createFiberRoot(
  containerInfo: any,
  tag: RootTag,
  hydrate: boolean,
  hydrationCallbacks: null | SuspenseHydrationCallbacks,
): FiberRoot {
  const root: FiberRoot = (new FiberRootNode(containerInfo, tag, hydrate): any);

  // Cyclic construction. This cheats the type system right now because
  // stateNode is any.
  const uninitializedFiber = createHostRootFiber(tag);
  root.current = uninitializedFiber;
  uninitializedFiber.stateNode = root;

  initializeUpdateQueue(uninitializedFiber);

  return root;
}

FiberRootNode結構:

// react-reconciler/src/ReactFiberRoot.js
function FiberRootNode(containerInfo, tag, hydrate) {
  this.tag = tag;
  this.current = null;
  this.containerInfo = containerInfo;
  this.pendingChildren = null;
  this.context = null;
  this.hydrate = hydrate; // false
  ......
}

createHostRootFiber -> createFiber -> 返回 FiberNode結構:

// react-reconciler/src/ReactFiber.js
export function createHostRootFiber(tag: RootTag): Fiber {
  ......
  // mode = NoMode
  return createFiber(HostRoot, null, null, mode);
}

const createFiber = function(
  tag: WorkTag,
  pendingProps: mixed,
  key: null | string,
  mode: TypeOfMode,
): Fiber {
  // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
  return new FiberNode(tag, pendingProps, key, mode);
};

function FiberNode(
  tag: WorkTag,
  pendingProps: mixed,
  key: null | string,
  mode: TypeOfMode,
) {
  // Instance
  this.tag = tag;
  this.key = key;
  this.elementType = null;
  this.type = null;
  this.stateNode = null;

  // Fiber
  this.return = null;
  this.child = null;
  this.sibling = null;
  this.index = 0;

  this.ref = null;

  this.pendingProps = pendingProps;
  this.memoizedProps = null;
  this.updateQueue = null;
  this.memoizedState = null;
  this.dependencies_old = null;

  this.mode = mode;
  ......
}

initializeUpdateQueue:

// react-reconciler/src/ReactUpdateQueue.js
export function initializeUpdateQueue<State>(fiber: Fiber): void {
  const queue: UpdateQueue<State> = {
    baseState: fiber.memoizedState,
    firstBaseUpdate: null,
    lastBaseUpdate: null,
    shared: {
      pending: null,
    },
    effects: null,
  };
  fiber.updateQueue = queue;
}

創(chuàng)建好 root 后,返回到【3. legacyRenderSubtreeIntoContainer】,調用 updateContainer 進行渲染。

root 是個對象:

root._internalRoot = FiberRootNode;                       // legacyRenderSubtreeIntoContainer中 this._internalRoot 賦值
root._internalRoot.current = FiberNode;                   // createFiberRoot
root._internalRoot.current.stateNode = root._internalRoot;// createFiberRoot

二、回顧一下 render 的整體調用鏈

render.png

三、總結

ReactDOM.render源碼就先學習到這,至于 updateContainer ,涉及到 Fiber 及其 Scheduler 機制,之后會繼續(xù)學習。Fiber 也是 React v16 推出的一個重點,提升了 React 的渲染性能。

?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容