旧生命周期
原理图:
可见,react包含如下生命周期函数:
1.constructor()
2.componentWillMount()
3.render()
4.componentDIdMount()
5.componentWillUnmount()
6.componentWillReceiveProps()
7.shouldComponentUpdate()
8.componentWillUpdate()
9.componentDIdUpdate()
其中3,4,5是最常用的,带“”will“”的2,6,8官方不推荐使用,并且提示加前缀UNSAFE_使用。
重要的钩子
render()初始化渲染或更新渲染调用
componentDIdMount()开启监听,发送Ajax请求,开启定时器等
componentWillUnmount()做一些收尾工作,清理定时器等
即将废弃的钩子
componentWillMount()
componentWillReceiveProps()
componentWillUpdate()
新生命周期
原理图:
果然是移除了那三个钩子,新增了两个 :
1.getDerivedStateFromProps()
2.getSnapshotBeforeUpdate()
1.getDerivedStateFromProps()使用场景:若state的值在任何时候都取决于props,那么可以使用
2.getSnapshotBeforeUpdate():在更新之前获取快照。