簡體   English   中英

為什么在 componentDidUpdate 中使用 setState 在 React 中被視為不好的做法?

[英]Why is using setState inside componentDidUpdate seen as a bad practice in React?

當道具更新時,我需要更新孩子的狀態,所以我做了這樣的事情:

componentDidUpdate(prevProps) {
    const { searchValue, searchCriterion } = this.props;

    if (searchValue !== prevProps.searchValue) {
      this.setState({ searchValue });
    }
    if (searchCriterion !== prevProps.searchCriterion) {
      this.setState({ searchCriterion });
    }
  }

ESLint 的 airbnb 指南正在抱怨它並拋出這個警告,即使我看不到任何明顯的渲染或性能問題。

警告說:

在組件更新后更新狀態將觸發第二次 render() 調用,並可能導致屬性/布局抖動。

當道具具有新值時,是否有更好的方法來更新孩子的狀態?

或者我應該忽略警告?

您的代碼的問題是它可能會創建一個無限循環。 當您調用setState方法時,您會觸發第二次render ,就像警告所說的那樣,因此會觸發一個新的componentDidUpdate

為了解決這個問題,您可能希望為狀態的某些值創建一個中斷條件以退出循環。 例如,您可以簡單地使用如下標志:

componentDidUpdate(prevProps) {
const { searchValue, searchCriterion } = this.props;

if (this.state.isAlreadyUpdated === true) {
  this.setState({ isAlreadyUpdated: false });
  break;
} else {
  this.setState({ isAlreadyUpdated: true });
}

if (searchValue !== prevProps.searchValue) {
  this.setState({ searchValue });
}
if (searchCriterion !== prevProps.searchCriterion) {
  this.setState({ searchValue });
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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