ReactDom render原理剖析

複習一下經常寫的JSX

ReactDOM.render(
    <h1>Hello World</h1>, 
    document.getElementById('root')
);

// babel 轉義以後,JSX語法實際上是React.createElement()的語法糖
ReactDOM.render(React.createElement(
    'h1', // type--節點類型
    null, // props
    'Hello World' // children
), document.getElementById('root'));

// createElement 部分代碼詳細過程不作分析
export function createElement(type, config, children) {
  ...
  // 返回一個ReactElement
  return ReactElement(
    type,
    key,
    ref,
    self,
    source,
    ReactCurrentOwner.current,
    props,
  );
}
// ReactElement 部分代碼
const ReactElement = function(type, key, ref, self, source, owner, props) {
  const element = {
    // 標記惟一識別的元素類型
    $$typeof: REACT_ELEMENT_TYPE,
    // 元素的內置類型
    type: type,
    key: key,
    ref: ref,
    props: props,
    // 記錄建立此元素的組件
    _owner: owner,
  };
  ...
  return element; // 最後返回一個element
 }
複製代碼

createElement對應的源碼部分是ReactElement.js,感興趣能夠本身看看html

這裏不細說JSX,感興趣能夠看看官網介紹JSXreact


ReactDom.render 本地渲染過程

版本16以前,不作分析,詳細過程參考連接 ReactDom 組件渲染過程git

版本16以後,渲染過程分析

聲明一個簡單組件github

class Simple extends React.Component {
  render() {
    return (
      <h1>Simple test</h1>
    )
  }
}
console.log(<Simple />); 複製代碼

通過babel轉義以後chrome

var Simple = (function(_React$Component2) {
  // 繼承 Component 的屬性和方法
  _inherits(Simple, _React$Component2);

  function Simple() {
    _classCallCheck(this, Simple);

    return _possibleConstructorReturn(
      this,
      (Simple.__proto__ || Object.getPrototypeOf(Simple)).apply(this, arguments)
    );
  }

  _createClass(Simple, [
    {
      key: "render",
      value: function render() {
        return _react2.default.createElement("h1", null, "Simple text");
      }
    }
  ]);

  return Simple;
})(_react2.default.Component);

// 直接打印的是 createElement 返回的對象: 包括當前節點的全部信息。 即: `render` 方法
console.log(_react2.default.createElement(Simple, null));

// 實際返回 構造函數。
exports.default = Simple;
複製代碼

打印結果數組

{$$typeof: Symbol(react.element), type: ƒ, key: null, ref: null, props: {…}, …}
  $$typeof:Symbol(react.element)
  key:null
  props:{}
  ref:null
  type:ƒ Simple()
  _owner:null
  _store:{validated: false}
  _self:null
  _source:{fileName: "D:\CodeSpace\Scheele2\src\index.js", lineNumber: 33}
  __proto__:Object
複製代碼

組件的掛載

先看chrome瀏覽器render過程,給你們一個印象,而後根據函數,逐一分析涉及DOM的部分 瀏覽器

render --ReactDOM.render

源碼位置babel

const ReactDOM: Object = {
    ...
 render(
    element: React$Element<any>,
    container: DOMContainer,
    callback: ?Function,
  ) {
    return legacyRenderSubtreeIntoContainer(
      null, // parent
      element, // children
      container, // Dom容器
      false, // 渲染標記
      callback, // 回調
    );
  },
}
複製代碼

legacyRenderSubtreeIntoContainer

// 結合上方的render函數來看
function legacyRenderSubtreeIntoContainer( parentComponent: ?React$Component<any, any>, children: ReactNodeList, container: DOMContainer, forceHydrate: boolean, callback: ?Function, ) {
 ...
 let root: Root = (container._reactRootContainer: any);
  if (!root) {
    // 初始化掛載,得到React根容器對象
    root = container._reactRootContainer = legacyCreateRootFromDOMContainer(
      container,
      forceHydrate,
    );
}
}
複製代碼

ReactDOM.legacyCreateRootFromDOMContainer

function legacyCreateRootFromDOMContainer( container: DOMContainer, forceHydrate: boolean, // 渲染標記 ): Root {
  const shouldHydrate =
    forceHydrate || shouldHydrateDueToLegacyHeuristic(container);
  // 第一次渲染,刪除其他的全部節點
  if (!shouldHydrate) {
    let warned = false;
    let rootSibling;
    while ((rootSibling = container.lastChild)) {
      ...
      container.removeChild(rootSibling);
    }
  }
  ...
  const isAsync = false; // 是否異步
 // 返回一個根節點對象
  return new ReactRoot(container, isAsync, shouldHydrate);
}
  ...
// 經過DOMRenderer建立一個root
function ReactRoot(container: Container, isAsync: boolean, hydrate: boolean) {
  const root = DOMRenderer.createContainer(container, isAsync, hydrate);
  this._internalRoot = root;
}
複製代碼

源碼位置app

// createContainer涉及到了React新推出的Fiber
export function createContainer( containerInfo: Container, isAsync: boolean, hydrate: boolean, ): OpaqueRoot {
  return createFiberRoot(containerInfo, isAsync, hydrate);
}
複製代碼

源碼位置dom

// 最終返回的對象
export function createFiberRoot( containerInfo: any, isAsync: boolean, hydrate: boolean, ): FiberRoot {
 ...
 // 沒有改形成Fiber以前,節點類型可能就幾種,Fiber以後嘛...
 // 這裏是將節點初始化成Fiber的節點,感興趣能夠看看Fiber,這裏不細說
 const uninitializedFiber = createHostRootFiber(isAsync);
 let root;
 // 這個是個 export const enableSchedulerTracing = __PROFILE__;
  if (enableSchedulerTracing) {
   ...
  }else {
   // 最後返回的root對象
    root = ({
      current: uninitializedFiber,
      containerInfo: containerInfo, // DOM容器
      pendingChildren: null,

      earliestPendingTime: NoWork,
      latestPendingTime: NoWork,
      earliestSuspendedTime: NoWork,
      latestSuspendedTime: NoWork,
      latestPingedTime: NoWork,

      didError: false,

      pendingCommitExpirationTime: NoWork,
      finishedWork: null,
      timeoutHandle: noTimeout,
      context: null,
      pendingContext: null,
      hydrate,
      nextExpirationTimeToWorkOn: NoWork,
      expirationTime: NoWork,
      firstBatch: null,
      nextScheduledRoot: null,
    }: BaseFiberRootProperties);
  }
  uninitializedFiber.stateNode = root;
  return ((root: any): FiberRoot);
}
...
複製代碼

unbatchedUpdates

初始化root對象完成以後,調用unbatchedUpdates函數

// 無論是if,仍是else,本質上都是初始化work = new ReactWork(),而後執行updateContainer操做
 DOMRenderer.unbatchedUpdates(() => {
      if (parentComponent != null) { // 若是根節點不爲空,將節點渲染進去
        root.legacy_renderSubtreeIntoContainer(
          parentComponent,
          children,
          callback,
        );
      } else { // 渲染根節點
        root.render(children, callback);
      }
    });
...
複製代碼

ReactRoot.render,updateContainer

ReactRoot.prototype.render = function( children: ReactNodeList, callback: ?() => mixed, ): Work {
  const root = this._internalRoot;
  const work = new ReactWork();
  callback = callback === undefined ? null : callback;
  ...
  if (callback !== null) {
    work.then(callback);
  }
  // 執行updateContainer函數,返回一個work對象(參數就不解釋了吧...)
  DOMRenderer.updateContainer(children, root, null, work._onCommit);
  return work;
};
複製代碼

剩下的調用過程(這裏主要是react-reconciler部分的代碼)

代碼量過多,先貼出調用過程

源碼位置

// 這些函數調用的過程,能夠簡單理解成是爲了配合Fiber的批度更新以及異步更新而進行的
updateContainerAtExpirationTime(element,container,parentComponent,expirationTime,callback)->
scheduleRootUpdate(current, element, expirationTime, callback) ->
scheduleWork(current, expirationTime) ->
requestWork(root, rootExpirationTime) ->
performWorkOnRoot(root, Sync, false) ->
renderRoot(root, false) -> 
workLoop(isYieldy) -> // 開啓一個循環過程,這個函數仍是挺有意思的
performUnitOfWork(nextUnitOfWork: Fiber) => Fiber | null ->
beginWork(current, workInProgress, nextRenderExpirationTime) // 這個函數開啓一個work流程
複製代碼

beginWork

主要做用是根據Fiber對象的tag來對組件進行mount或update

function beginWork( current: Fiber | null, workInProgress: Fiber, renderExpirationTime: ExpirationTime, ): Fiber | null {
  const updateExpirationTime = workInProgress.expirationTime; // 更新所需時間
  if (
    !hasLegacyContextChanged() &&
    (updateExpirationTime === NoWork ||updateExpirationTime > renderExpirationTime)
  ) {
    ...
  switch (workInProgress.tag) {
    case IndeterminateComponent: { // 不肯定的組件類型
     ...
    }
    case FunctionalComponent: { // 函數類型組件
      ...
    }
    ...
    case ClassComponent: { // 對應咱們以前建立的組件 Simple
      const Component = workInProgress.type;
      const unresolvedProps = workInProgress.pendingProps;
      // 返回一個classComponent
      return updateClassComponent(
        current,
        workInProgress,
        Component,
        unresolvedProps,
        renderExpirationTime,
      );
    }
    ...
    case HostRoot: // 對應根節點
      return updateHostRoot(current, workInProgress, renderExpirationTime);
    case HostComponent: // 對應 <h1 />
      return updateHostComponent(current, workInProgress, renderExpirationTime);
    case HostText: // 對應Simple test
      return updateHostText(current, workInProgress);
    ... // 後面還有就不一一列舉了,感興趣能夠本身看
  }
複製代碼

updateClassComponent

主要做用是對未初始化的組件進行初始化,對已初始化的組件進行更新和重用

function updateClassComponent( current: Fiber | null, workInProgress: Fiber, Component: any, nextProps, renderExpirationTime: ExpirationTime, ) {
    ...
  if (current === null) {
    if (workInProgress.stateNode === null) {
      // 實例化類組件
      constructClassInstance(
        workInProgress, // Fiber更新進度標識
        Component, // 組件
        nextProps, // props
        renderExpirationTime, // 所需時間
      );
      // 初始化mount
      mountClassInstance(
        workInProgress,
        Component,
        nextProps,
        renderExpirationTime,
      );
      shouldUpdate = true;
    } else {
      // 若是已經建立實例,則重用
      shouldUpdate = resumeMountClassInstance(
        workInProgress,
        Component,
        nextProps,
        renderExpirationTime,
      );
    }
 } else {
    shouldUpdate = updateClassInstance(
      current,
      workInProgress,
      Component,
      nextProps,
      renderExpirationTime,
    );
  }
  return finishClassComponent(
    current,
    workInProgress,
    Component,
    shouldUpdate,
    hasContext,
    renderExpirationTime,
  );
 }
 ...
}
複製代碼

mountClassInstance

主要是掛載一些新的生命週期函數,除了比較熟悉的componentWillMount外,還有dev環境下的警告生命週期函數,以及16後才推出的getDerivedStateFromProps

function mountClassInstance( workInProgress: Fiber, ctor: any, newProps: any, renderExpirationTime: ExpirationTime, ): void {
  ...
  if (__DEV__) {
    if (workInProgress.mode & StrictMode) {
      ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(
        workInProgress,
        instance,
      );
      ReactStrictModeWarnings.recordLegacyContextWarning(
        workInProgress,
        instance,
      );
    }
    if (warnAboutDeprecatedLifecycles) {
      ReactStrictModeWarnings.recordDeprecationWarnings(
        workInProgress,
        instance,
      );
    }
  }
  // 處理狀態更新的操做
  let updateQueue = workInProgress.updateQueue;
  if (updateQueue !== null) {
    processUpdateQueue(
      workInProgress,
      updateQueue,
      newProps,
      instance,
      renderExpirationTime,
    );
    instance.state = workInProgress.memoizedState;
  }
  const getDerivedStateFromProps = ctor.getDerivedStateFromProps;
  if (typeof getDerivedStateFromProps === 'function') { // 掛載新的生命週期函數
    applyDerivedStateFromProps(
      workInProgress,
      ctor,
      getDerivedStateFromProps,
      newProps,
    );
    instance.state = workInProgress.memoizedState;
  }
    if (
    typeof ctor.getDerivedStateFromProps !== 'function' &&
    typeof instance.getSnapshotBeforeUpdate !== 'function' &&
    (typeof instance.UNSAFE_componentWillMount === 'function' ||
      typeof instance.componentWillMount === 'function')
  ) {
    // 若是沒有使用getDerivedStateFromProps就使用componentWillMount
    callComponentWillMount(workInProgress, instance);
    // 若是在這個生命週期中有狀態更新,則立刻開始處理它
    updateQueue = workInProgress.updateQueue;
    if (updateQueue !== null) {
      processUpdateQueue(
        workInProgress,
        updateQueue,
        newProps,
        instance,
        renderExpirationTime,
      );
      instance.state = workInProgress.memoizedState;
    }
  }
  if (typeof instance.componentDidMount === 'function') {
    workInProgress.effectTag |= Update;
  }
  // 因此說使用getDerivedStateFromProps這個新的狀態函數,第一次加載跟更新都會當即執行
}
複製代碼

finishClassComponent

調用組件實例的render函數獲取須要處理的子元素,並把子元素處理爲Fiber類型,處理state和props

function finishClassComponent( current: Fiber | null, workInProgress: Fiber, Component: any, shouldUpdate: boolean, hasContext: boolean, renderExpirationTime: ExpirationTime, ) {
 ...
  // 把子元素轉換爲Fiber類型,若是子元素爲數組的時候,返回第一個Fiber類型子元素
   reconcileChildren( // 感興趣能夠去github看看源碼的說明
    current,
    workInProgress,
    nextChildren,
    renderExpirationTime,
  );
  // TODO: Restructure so we never read values from the instance.
  // 處理state和props
  memoizeState(workInProgress, instance.state);
  memoizeProps(workInProgress, instance.props);
  if (hasContext) {
    invalidateContextProvider(workInProgress, Component, true);
  }
  // 返回Fiber類型的子元素
  return workInProgress.child;
}
複製代碼

workLoop

workLoop遍歷虛擬DOM樹,調用performUnitOfWork對子元素進行處理。

function workLoop(isYieldy) {
  if (!isYieldy) {
    // 循環遍歷整棵樹
    while (nextUnitOfWork !== null) {
      nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
    }
  } else {
    // 一直遍歷,直到這一次的處理時間用完
    while (nextUnitOfWork !== null && !shouldYield()) {
      nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
    }
  }
}
複製代碼

performUnitOfWork

調用beginWork對子元素進行處理返回,沒有新工做產生,調用completeUnitOfWork開始轉換

function performUnitOfWork(workInProgress: Fiber): Fiber | null {
  const current = workInProgress.alternate;
  // 檢查是否有其它工做須要展開
  startWorkTimer(workInProgress);
  ...
  let next;
  // 判斷是否在一個更新時間內
  if (enableProfilerTimer) {
    if (workInProgress.mode & ProfileMode) {
      startProfilerTimer(workInProgress);
    }
    next = beginWork(current, workInProgress, nextRenderExpirationTime);
    if (workInProgress.mode & ProfileMode) {
      // 記錄渲染時間
      stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true);
    }
  } else {
    next = beginWork(current, workInProgress, nextRenderExpirationTime);
  }
  ...
  if (next === null) {
    // 若是沒有新的工做產生,則完成當前工做
    next = completeUnitOfWork(workInProgress);
  }
  ReactCurrentOwner.current = null;
  return next;
}
複製代碼

completeUnitOfWork

主要做用是將Fiber節點元素轉換爲真實的DOM節點

function completeUnitOfWork(workInProgress: Fiber): Fiber | null {
  while (true) {
    const returnFiber = workInProgress.return; // 父節點
    const siblingFiber = workInProgress.sibling; // 兄弟節點
    if ((workInProgress.effectTag & Incomplete) === NoEffect) {
      // 在一次渲染週期內
      if (enableProfilerTimer) {
        if (workInProgress.mode & ProfileMode) {
          startProfilerTimer(workInProgress);
        }
        // 調用completeWork轉換虛擬DOM
        nextUnitOfWork = completeWork(
          current,
          workInProgress,
          nextRenderExpirationTime,
        );
        if (workInProgress.mode & ProfileMode) {
          // 更新渲染時間
          stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
        }
      } else {
        nextUnitOfWork = completeWork(
          current,
          workInProgress,
          nextRenderExpirationTime,
        );
      }
      let next = nextUnitOfWork;
      stopWorkTimer(workInProgress); // 結束一個work
      resetChildExpirationTime(workInProgress, nextRenderExpirationTime);
      ...
      if (next !== null) { // 若是還有新的工做,return回去,繼續執行
        stopWorkTimer(workInProgress);
        return next;
      }
      // 這個地方就不註釋了,源碼裏面已經解釋的足夠清楚
      if (
        returnFiber !== null &&
        // Do not append effects to parents if a sibling failed to complete
        (returnFiber.effectTag & Incomplete) === NoEffect
      ) {
        // Append all the effects of the subtree and this fiber onto the effect
        // list of the parent. The completion order of the children affects the
        // side-effect order.
        if (returnFiber.firstEffect === null) {
          returnFiber.firstEffect = workInProgress.firstEffect;
        }
        if (workInProgress.lastEffect !== null) {
          if (returnFiber.lastEffect !== null) {
            returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
          }
          returnFiber.lastEffect = workInProgress.lastEffect;
        }
        // If this fiber had side-effects, we append it AFTER the children's
        // side-effects. We can perform certain side-effects earlier if
        // needed, by doing multiple passes over the effect list. We don't want
        // to schedule our own side-effect on our own list because if end up
        // reusing children we'll schedule this effect onto itself since we're
        // at the end.
        const effectTag = workInProgress.effectTag;
        // Skip both NoWork and PerformedWork tags when creating the effect list.
        // PerformedWork effect is read by React DevTools but shouldn't be committed.
        if (effectTag > PerformedWork) {
          if (returnFiber.lastEffect !== null) {
            returnFiber.lastEffect.nextEffect = workInProgress;
          } else {
            returnFiber.firstEffect = workInProgress;
          }
          returnFiber.lastEffect = workInProgress;
        }
      }
      ...
      if (siblingFiber !== null) {
        // 若是有兄弟節點,則返回一個兄弟節點
        return siblingFiber;
      } else if (returnFiber !== null) {
        // 完成此次工做
        workInProgress = returnFiber;
        continue;
      } else {
        // 已經遍歷到了根部
        return null;
      }
    }  
  }else{
    ... // 感興趣本身看 
  }
  return null;
}
複製代碼

completeWork

根據Fiber節點類型進行處理,渲染真實DOM

function completeWork( current: Fiber | null, workInProgress: Fiber, renderExpirationTime: ExpirationTime, ): Fiber | null {
  ...
  switch (workInProgress.tag) {
    ...
    // 只看重點代碼
    case HostComponent: {
      popHostContext(workInProgress);
      const rootContainerInstance = getRootHostContainer();
      const type = workInProgress.type;
      if (current !== null && workInProgress.stateNode != null) {
        // 更新
        updateHostComponent(
          current,
          workInProgress,
          type,
          newProps,
          rootContainerInstance,
        );
        if (current.ref !== workInProgress.ref) {
          markRef(workInProgress);
        }
      } else {
        ...
        const currentHostContext = getHostContext();
        let wasHydrated = popHydrationState(workInProgress);
        if (wasHydrated) {
          ...
        } else {
          // 建立並返回DOM元素
          let instance = createInstance(
            type,
            newProps,
            rootContainerInstance,
            currentHostContext,
            workInProgress,
          );
          // 添加節點
          appendAllChildren(instance, workInProgress);
          // 判斷是否有其它的渲染器,進行標記
          if (
            finalizeInitialChildren(
              instance,
              type,
              newProps,
              rootContainerInstance,
              currentHostContext,
            )
          ) {
            markUpdate(workInProgress);
          }
          workInProgress.stateNode = instance;
        }
        if (workInProgress.ref !== null) {
          // 若是有ref,則須要調用
          markRef(workInProgress);
        }
      }
      break;
    }
  }
}
複製代碼

簡單的總結

  1. 首先咱們寫的JSX語法,都被Babel進行轉義,而後使用React.creatElement進行建立,轉換爲React的元素
  2. 使用ReactDom.render建立root對象,執行root.render。
  3. 一系列函數調用以後,workLoop在一次渲染週期內,遍歷虛擬DOM,將這些虛擬DOM傳遞給performUnitOfWork函數,performUnitOfWork函數開啓一次workTime,將虛擬DOM傳遞給beginWork。
  4. beginWork根據虛擬DOM的類型,進行不一樣的處理,將子元素處理爲Fiber類型,爲Fiber類型的虛擬DOM添加父節點、兄弟節點等(就是轉換爲Fiber樹)。
  5. beginWork處理完一次操做以後,返回須要處理的子元素再繼續處理,直到沒有子元素(即返回null),
  6. 此時performUnitOfWork調用completeUnitOfWork進行初始化生命週期的掛載,以及調用completeWork進行DOM的渲染。
  7. completeWork對節點類型進行操做,發現是html相關的節點類型,添加渲染爲真實的DOM。
  8. 最後將全部的虛擬DOM,渲染爲真實的DOM。

組件的卸載 todo.

服務端渲染過程 todo.

將來的瞎扯

在查看源碼的過程當中,發現涉及異步的操做,都寫上了unstable,而這些異步的操做,纔是Fiber這個利器展示獠牙的時候,在將來的某個時刻,我會補上這部分的東西

ps: 有不對的地方歡迎斧正

相關文章
相關標籤/搜索