文章目录
- 1. 组件的生命周期
- 1.1 理解
- 1.2 引入案例
- 1.3 生命周期的三个阶段(旧)
- 1.3.1 初始化阶段
- 1.3.2 更新阶段
- 1.3.3 卸载组件
- 总结:
- 1.4 生命周期的三个阶段(新)
- getDerivedStateFromProps
- getSnapshotBeforeUpdate
- 总结:
- 1. 初始化阶段
- 2. 更新阶段
- 3. 卸载组件
- 1.5 重要的勾子
- 1.6 即将废弃的勾子
1. 组件的生命周期
1.1 理解
组件从创建到死亡它会经历一些特定的阶段。
React组件中包含一系列勾子函数(生命周期回调函数), 会在特定的时刻调用。
我们在定义组件时,会在特定的生命周期回调函数中,做特定的工作。
1.2 引入案例
需求:定义组件实现以下功能:
- 让指定的文本做显示 / 隐藏的渐变动画
- 从完全可见,到彻底消失,耗时2S
- 点击“不活了”按钮从界面中卸载组件
1.3 生命周期的三个阶段(旧)
1.3.1 初始化阶段
由ReactDOM.render()
触发—初次渲染
-
constructor()
—— 类组件中的构造函数 -
componentWillMount()
—— 组件将要挂载 【即将废弃】 -
render()
—— 挂载组件 -
componentDidMount()
—— 组件挂载完成 比较常用
一般在这个钩子中做一些初始化的事,例如:开启定时器、发送网络请求、订阅消息
1.3.2 更新阶段
- 【第一种情况】父组件重新
render
触发
componentWillReceiveProps()
—— 接收属性参数(非首次)【即将废弃】
然后调用下面的钩子函数
- 【第二种情况】由组件内部
this.setSate()
shouldComponentUpdate()
—— 组件是否应该被更新(默认返回true)
然后调用下面的钩子函数 - 【第三种情况】强制更新
forceUpdate()
-
componentWillUpdate()
——组件将要更新 【即将废弃】 -
render()
—— 组件更新 -
componentDidUpdate()
—— 组件完成更新
1.3.3 卸载组件
由ReactDOM.unmountComponentAtNode()
触发
componentWillUnmount()
—— 组件即将卸载
总结:
1.4 生命周期的三个阶段(新)
getDerivedStateFromProps
这样的话,state在任何时候,都取决于props
getSnapshotBeforeUpdate
总结:
1. 初始化阶段
由ReactDOM.render()
触发 —— 初次渲染
-
constructor()
—— 类组件中的构造函数 -
static getDerivedStateFromProps(props, state)
从props得到一个派生的状态【新增】 -
render()
—— 挂载组件 -
componentDidMount()
—— 组件挂载完成 比较常用
2. 更新阶段
由组件内部this.setSate()
或父组件重新render触发或强制更新forceUpdate()
-
getDerivedStateFromProps()
—— 从props得到一个派生的状态 【新增】 -
shouldComponentUpdate()
—— 组件是否应该被更新(默认返回true) -
render()
—— 挂载组件 -
getSnapshotBeforeUpdate()
—— 在更新之前获取快照【新增】 -
componentDidUpdate(prevProps, prevState, snapshotValue)
—— 组件完成更新
3. 卸载组件
由ReactDOM.unmountComponentAtNode()
触发
componentWillUnmount()
—— 组件即将卸载
1.5 重要的勾子
render
:初始化渲染或更新渲染调用
componentDidMount
:开启监听, 发送ajax请求
componentWillUnmount
:做一些收尾工作, 如: 清理定时器
1.6 即将废弃的勾子
componentWillMount
componentWillReceiveProps
componentWillUpdate
现在使用会出现警告,下一个大版本需要加上UNSAFE_前缀才能使用,以后可能会被彻底废弃,不建议使用。
参考:
【React】组件的生命周期- 虚拟DOM - DOM Diffing算法