React 新旧生命周期
新生命周期
如下图所示:
后面17中即将废弃的三个生命周期
componentWillMount
componentWillMountcomponentWillReceiveProps
componentWillReceivePropscomponentWillUpdate
componentWillUpdate说明
目前在16版本中
componentWillMount,componentWillReceiveProps,componentWillUpdate并未完全删除这三个生命周期函数,而且新增了UNSAFE_componentWillMount,UNSAFE_componentWillReceiveProps,UNSAFE_componentWillUpdate三个函数,官方计划在17版本完全删除这三个函数,只保留UNSAVE_前缀的三个函数,目的是为了向下兼容,但是对于开发者而言应该尽量避免使用他们,而是使用新增的生命周期函数替代它们。
挂载阶段
construct
construct(props)
作用
- 获取
this对象 【 super(props) 】 - 初始化
state状态数据 - 自定义方法
this绑定 说明
- 该构造函数方法中不要使用
setState()方法,使用this.state赋予state初始值 - 避免在构造函数中引入任何副作用或订阅【该些操作应放入
componentDidMount函数中】
getDerivedStateFromProps
static getDerivedStateFromProps(nextProps, prevState)
1、参数:
- props: 最新的
props参数 - state: 之前的
state2、返回值: - 返回新的
state对象或null说明 - 函数内部不能访问
this对象,即无法获取this.state和this.props - 在挂载时接受到新的
props,组件内调用setState和forceUpdate也会调用 - 取代旧生命周期的
componentWillMountcomponentWillReceivePropscomponentWillUpdate
render
componentDidMount
更新阶段
getDerivedStateFromProps
shouldComponentUpdate
shouldComponentUpdate(nextProps, nextState)
1、参数
- nextProps: 最新的
props参数 - nextState: 即将需要更新的
state对象 2、返回值【boolean类型】 - ture: 默认值,更新渲染
- false: 不更新渲染 说明
- 在挂载时接受到新的
props,组件内调用setState和forceUpdate也会调用 - 返回
false并不会阻止子组件在state更改时重新渲染 - 不建议在
shouldComponentUpdate()中进行深层比较或使用JSON.stringify()。这样非常影响效率,且会损害性能
render
getSnapshotBeforeUpdate
getSnapshotBeforeUpdate(prevProps, prevState)
1、参数
-
prevProps: 之前的
props -
prevState: 之前的
state2、返回值 -
返回值作为
componentDidUpdate周期函数的第三个参数值,无传递值时返回null说明 -
替代
componentWillUpdate周期函数
componentDidUpdate
componentDidUpdate(prevProps, prevState, snapshot)
1、参数
- prevProps: 之前的
props - prevState: 之前的
state - snapshot:
getSnapshotBeforeUpdate周期函数的返回值, 默认值为undefined说明 - 可以操作
DOM,和发起服务器请求,还可以setState - 注意一定要用
if语句控制,否则会导致无限循环 - 当
shouldComponentUpdate返回值为false时,不会调用该周期函数
卸载阶段
componentWillUnmount
componentWillUnmount()
说明
- 主要用于清楚一些定时器,取消网络请求,清理无效的
DOM元素等垃圾清理工作 - 在该函数内调用
setState方法,组件不会再进行重新渲染
旧生命周期
挂载阶段
construct
componentWillMount/UNSAFE_componentWillMount
componentWillMount()
说明
- 该周期函数在
render方法之前调用,所以setState不会触发重新渲染
render
componentDidMount
更新阶段
componentWillReceiverProps/UNSAFE_componentWillReceiveProps
componentWillReceicerProps(nextProps)
1、参数
- nextProps: 最新的
props参数
说明
- 一般通过比较
nextProps和this.props值然后使用setState方法对state进行更新控制处理 - 父组件重新渲染,
props值不变时仍然会触发调用该周期函数 - 装载阶段【挂载阶段】不会触发,以及在组件内部调用了
setState和forceUpdate也不会触发这两个函数
shouldComponentUpdate
componentWillUpdate/UNSAFE_componentWillUpdate
componentWillUpdate(nextProps, nextState)
1、参数
- nextProps: 最新的
props参数 - nextState: 即将要更新的
state对象 说明 - 函数中不能执行
setState方法 【此时下一个state状态已经被确定,马上就要执行render重新渲染了,否则会导致整个生命周期混乱】 - 不能请求一些网络数据,因为在异步渲染中,可能会导致网络请求多次,引起一些性能问题
- 如果你在这个方法里保存了滚动位置,也是不准确的,还是因为异步渲染的问题,如果你非要获取滚动位置的话,请在
getSnapshotBeforeUpdate调用