componentDidUpdate
与componentWillReceiveProps
区别主要有两点:一是触发的时机;二是在这两个方法中调用更新状态方法后如何更新组件状态。
- 触发时机
先上一张react生命周期图(图片来源:图解ES6中的React生命周期)
componentDidUpdate
有两个参数prevProps
和prevState
,无论是父组件props的修改还是状态的更改都会触发该方法,而componentWillReceiveProps
只有在父组件重新render props改变的时候会触发。
应用场景:当你希望只有在接收到新props时做一些逻辑时,请使用
componentWillReceiveProps
,如:根据父组件传入的数据初始化或重置某些内部状态。若希望无论props更改还是组件内容状态更改都能触发一些逻辑,那么请使用componentDidUpdate
。
- 两个方法是如何更新组件状态的
若要在props更改时同步更新组件状态,使用
componentWillReceiveProps
;否则使用componentDidUpdate
。
关于componentWillReceiveProps
生命周期函数的逐渐替代方案:
react16.3:为不安全生命周期引入别名UNSAFE_componentWillMount,UNSAFE_componentWillReceiveProps和UNSAFE_componentWillUpdate。 (旧的生命周期名称和新的别名都可以在此版本中使用。)
后来的16.x版本:为componentWillMount,componentWillReceiveProps和componentWillUpdate启用弃用警告。 (旧的生命周期名称和新的别名都可以在此版本中使用,但旧名称会记录DEV模式警告。)
17.0:删除componentWillMount,componentWillReceiveProps和componentWillUpdate。 (从现在开始,只有新的“UNSAFE_”生命周期名称将起作用。)
后续将采用新的生命周期getDerivedStateFromProps
替代componentWillReceiveProps
,待研究透彻后将更新文档。