componentWillReceiveProps(nextProps) {
if(nextProps.count !== this.props.count)
// doSomething
}
}
componentDidUpdate(prevProps) {
if(prevProps.count !== this.props.count) {
this.setState({
count: this.props.count
})
}
}
在React生命周期调用时机
componentWillReceiveProps在组件接受新的props之前触发,
componentDidUpdate在组件接受新的props之后触发
如果你想在组件收到新props之前做一些事情,你可以使用componentWillReceiveProps,如果你想在收到新的props或状态后做某事,你可以使用componentDidUpdate
更新state的方式
componentWillReceiveProps更新状态是同步的
componentDidUpdate更新状态是异步的
这点区别非常重要,也是componentWillReceiveProps生命周期被废弃的重要原因(可能导致某些问题), 所以推荐使用componentDidUpdate