[React 源码] React 18.2 - 生命周期 [0.6k 字 - 阅读时长2min]

281 阅读2分钟

聊生命周期, 就是从类组件生命周期函数的角度来聊 React 的挂载和更新的渲染流程。

mount 阶段

React Reconcil 阶段 会在 beginWork 函数 中挂载类组件, 挂载的时候 再 constructClassInstance 函数中,先 new 类,执行 constructor 构造函数。初始化 stateprops

然后再 updateComponents 中继续执行,执行 mountClassInstance 函数,执行 getDeriveStateFromProps 生命周期函数 ,然后执行 componenWillMount 生命周期函数,新的生命周期已经废除了 componentWillMount

if (instance === null) {
    resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress);
    constructClassInstance(workInProgress, Component, nextProps);
    mountClassInstance(workInProgress, Component, nextProps, renderLanes);
    shouldUpdate = true;
  } 

之后,执行 render 函数,子节点开始进入 reconcil 阶段。 最后进入 commit 阶段,再 mutataion 阶段之后,再 layout 阶段 执行 componentDidMount 生命周期函数,此时 Dom 已经挂载完毕。

自此类组件挂载时的生命周期,执行完毕


update 阶段

更新的时候,调用 setState, React 又会从调用 scheduleUpdateOnFiber 从根节点开始调度更新,假设已经调度到该类组件。到达了该组件的 reconcil 阶段。reconcil 阶段 会在 beginWork 函数 中更新该类组件, 更新的时候判断 instance !== null, current !== null, 所以会走 updateClassInstance 函数,在该函数中,先执行 componentWillReceiveProps 生命周期期函数 传入新的 props,新的生命周期中已经废除了 componentWillReceiveProps, 然后开始执行 processUpdateQueue 函数 进行更新计算新的 state。将计算出的新的 state 和 新的 props 传入并执行getDeriveStateFromProps 生命周期函数,该生命周期返回的状态和新的状态,进行合并。作为 Dom 提交时最终的状态。

然后执行 checkShouldComponentUpdate 函数,在该函数中执行 shouldComponentUpdate 生命周期函数。如果返回 true 则执行 componentWillUpdate 生命周期函数,新的生命周期中已经废除了 componentWillReceiveProps。之后,执行 render 函数,子节点开始进入 reconcil 阶段。

最后进入 commit 阶段,再 before mutataion 阶段 (Dom 更新前) 传入旧的 state 执行 getSnapshotBeforeUpdate 生命周期函数,再 layout 阶段(Dom 更新后) 执行 componentDidUpdate 生命周期函数(和 componentDidMount 是同一个函数),此时 Dom 已经更新完毕。

自此类组件更新时的生命周期,执行完毕

image.png