簡體   English   中英

應該組件更新中的突變狀態反應16.6.3

[英]Mutating state in shouldComponentUpdate react 16.6.3

由於react已棄用了許多Lifecycle Methods我發現,當使用reduxconnect時,我想使用componentDidUpdate來擴展component本地狀態。 問題是只有prevProps, prevState才傳遞給此函數。

這意味着我nextProps, nextStateshouldComponentUpdate 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM