生命周期就像是人的一生,在特定的时候担任特定的角色。
本文介绍的是新版本react的生命周期
新版的生命周期删除了旧版生命周期中的componentWillMount
、componentWillUpdate
和componentWillReceiveProps
三个钩子,新增了getDerivedStateFromProps
和getSnapshotBeforeUpdate
两个钩子。
初始化阶段
- constructor() // 构造器
- getDerivedStateFromProps() // state 的值在任何时候都取决于 props 使用该生命周期函数
- render()
- componentDidMount() // 组件挂载完毕的钩子
更新阶段
- getDerivedStateFromProps()
- shouldComponentUpdate() // 控制组件是否更新
- render()
- getSnapshotBeforeUpdate() // 组件更新前快照 return 的值会传到
componentDidUpdate
钩子中 - componentDidUpdate()
组件卸载阶段
- componentWillUnmount()
注意:调用
forceUpdate()
会调用getDerivedStateFromProps
、render
、getSnapshotBeforeUpdate
、componentDidUpdate
这四个钩子