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阶段:
- mount时:组件首先会经验constructor、getDerivedStateFromProps、componnetWillMount、render
- update时:组件首先会经验componentWillReceiveProps、getDerivedStateFromProps、shouldComponentUpdate、render
- error时:会调用getDerivedStateFromError
commit阶段
- mount时:组件会经验componnetDidMount
- update时:组件会调用getSnapshotBeforeUpdate、componnetDidUpdate
- unMount时:调用componnetWillUnmount
- 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