关于react.js:react源码解析11生命周期调用顺序

0次阅读

共计 1168 个字符,预计需要花费 3 分钟才能阅读完成。

react 源码解析 11. 生命周期调用程序

视频解说(高效学习):进入学习

往期文章:

1. 开篇介绍和面试题

2.react 的设计理念

3.react 源码架构

4. 源码目录构造和调试

5.jsx& 外围 api

6.legacy 和 concurrent 模式入口函数

7.Fiber 架构

8.render 阶段

9.diff 算法

10.commit 阶段

11. 生命周期

12. 状态更新流程

13.hooks 源码

14. 手写 hooks

15.scheduler&Lane

16.concurrent 模式

17.context

18 事件零碎

19. 手写迷你版 react

20. 总结 & 第一章的面试题解答

21.demo

各阶段生命周期执行状况

函数组件 hooks 的周期会在 hooks 章节解说,这一章的使命周期次要针对类组件,各阶段生命周期执行状况看下图:

  • render 阶段:

    1. mount 时:组件首先会经验 constructor、getDerivedStateFromProps、componnetWillMount、render
    2. update 时:组件首先会经验 componentWillReceiveProps、getDerivedStateFromProps、shouldComponentUpdate、render
    3. error 时:会调用 getDerivedStateFromError
  • commit 阶段

    1. mount 时:组件会经验 componnetDidMount
    2. update 时:组件会调用 getSnapshotBeforeUpdate、componnetDidUpdate
    3. unMount 时:调用 componnetWillUnmount
    4. error 时:调用 componnetDidCatch

其中红色的局部不倡议应用,须要留神的是 commit 阶段生命周期在 mutation 各个子阶段的执行程序,能够温习上一章

接下来依据一个例子来解说在 mount 时和 update 时更新的具体程序:

  • mount 时:首先会依照深度优先的形式,顺次构建 wip Fiber 节点而后切换成 current Fiber,在 render 阶段会顺次执行各个节点的 constructor、getDerivedStateFromProps/componnetWillMount、render,在 commit 阶段,也就是深度优先遍历向上冒泡的时候顺次执行节点的 componnetDidMount
  • update 时:同样会深度优先构建 wip Fiber 树,在构建的过程中会 diff 子节点,在 render 阶段,如果返现有节点的变动,例如上图的 c2,那就标记这个节点 Update Flag,而后执行 getDerivedStateFromProps 和 render,在 commit 阶段会顺次执行节点的 getSnapshotBeforeUpdate、componnetDidUpdate
正文完
 0