React生命周期就是包括从创建,初始化数据、编译模板、挂载DOM、渲染、更新渲染、卸载等一系列的过程
可以划分为三个阶段:创建阶段、更新阶段、卸载阶段
创建阶段:
constructor
getDerivedStateFromProps
render
componentDidMount
更新阶段:
getDerivedStateFromProps
shouldComponentUpdate
render
getSnapshotBeforeUpdate
componentDidUpdate
卸载阶段:
componentWillUnmount
新版生命周期:
旧的生命周期:
通过两个图的对比,可以发现新版的生命周期减少了以下三种方法:
- componentWillMount
- componentWillReceiveProps
- componentWillUpdate
其实这三个方法仍然存在,只是在前者加上了UNSAFE_前缀,如UNSAFE_componentWillMount,并不像字面意思那样表示不安全,而是表示这些生命周期的代码可能在未来的 react版本可能废除
同时也新增了两个生命周期函数:
- getDerivedStateFromProps
- getSnapshotBeforeUpdate