[英]Mutating state in shouldComponentUpdate react 16.6.3
由於react已棄用了許多Lifecycle Methods
我發現,當使用redux
和connect
時,我想使用componentDidUpdate
來擴展component
本地狀態。 問題是只有prevProps, prevState
才傳遞給此函數。
這意味着我nextProps, nextState
在shouldComponentUpdate
lifeCycle`中只有nextProps, nextState
nextState。
對我來說,執行以下操作本質上是錯誤的:
shouldComponentUpdate(nextProps) {
const { status_status } = nextProps;
if(status_status === "error") {
this.props.dispatch(resetStatus());
}
return true;
}
這肯定是一個antiPattern
,我不應該這樣做。
我怎樣才能再拿到nextProps
不使用shouldComponentUpdate
我有類似的情況,我發現getDerivedStateFromProps在這種情況下有用且合適。
static getDerivedStateFromProps(props, state) {
// now, you may dispatch checking the condition
// BTW, you will dispatch just using props
// props.dispatch()
// this.props.dispatch() // invalid
}
我從文檔中知道此注釋:
如果您需要根據道具的變化執行副作用(例如,數據獲取或動畫),請改用componentDidUpdate生命周期。
但是我只是分享我的經驗,只有getDerivedStateFromProps
工作的情況。
但是,我也建議您先使用componentDidUpdate
掛鈎。 如果一切對您都有利,那就堅持下去。 或者,如果您也面對使用componentDidUpdate
並使用getDerivedStateFromProps
感覺還不錯,那么您可以發表自己的見解和想法作為答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.