使用方法看起來一樣:
componentWillReceiveProps(nextProps) { if(nextProps.count !== this.props.count)
// doSomething } }
componentDidUpdate(prevProps) { if(prevProps.count !== this.props.count) { this.setState({ count: this.props.count }) }
}
區別:
生命周期調用時機不同
componentWillReceiveProps
在組件接受新的props之前觸發,
componentDidUpdate
在組件接受新的props之后觸發
更新state的方式
最主要的區別是
- componentWillReceiveProps更新狀態是同步的
- componentDidUpdate更新狀態是異步的
這點區別非常重要,也是componentWillReceiveProps生命周期被廢棄的重要原因(可能導致某些問題), 所以推薦使用componentDidUpdate