ReactJS-最大更新深度超过错误

时间:2020-04-03 01:54:14

标签: reactjs

我遇到错误:

已超过最大更新深度。当一个组件发生这种情况 重复调用componentWillUpdate内的setState或 componentDidUpdate。 React将嵌套更新的数量限制为 防止无限循环。

代码为:

  componentDidUpdate() {
    this._updateLocalStorage();

    if (this.state.searchValue !== "") {
      this.setState({
        filteredNotes: this.state.notes.filter(
          note =>
            note.text
              .toLowerCase()
              .indexOf(this.state.searchValue.toLowerCase()) !== -1
        )
      });
    } else {
      this.setState({
        filteredNotes: this.state.notes 
      });
    }
  }

Maximum Update Depth Exceeded Error

3 个答案:

答案 0 :(得分:1)

如果状态发生变化,则每次都会调用

componentDidUpdate

因此,您可能需要谨慎使用setState


严格遵守setState的条件。也许像下面这样:

一些注意事项:

  • 对象比较
  • 值/地址参考
componentDidUpdate(pervProps, prevState) {
  if (prevState.filteredNotes !== this.state.filteredNotes) {
    this._updateLocalStorage();
    if (this.state.searchValue !== "") {
      this.setState({
        filteredNotes: this.state.notes.filter(
          note =>
            note.text
              .toLowerCase()
              .indexOf(this.state.searchValue.toLowerCase()) !== -1
        )
      });
    } else {
      this.setState({
        filteredNotes: this.state.notes 
      });
    }
  }
}

答案 1 :(得分:1)

正在发生的事情:

  1. 一旦this.state.searchValue变为真实,它就会在CDM中更新状态
  2. 更新状态触发另一个CDM
  3. 步骤1.重复
  4. 第2步。重复
  5. 无尽更新...

您应该怎么做:

  1. 将CDU更新为此componentDidUpdate(prevProps, prevState)
  2. 将您的条件全部更新为:
if(this.state.searchValue !== "" && this.state.searchValue !== prevState.searchValue) {...}

答案 2 :(得分:1)

如果在主状态调用之前两个状态相等,则可以通过空比较来解决。另外,我对else条件进行了更改。

  componentDidUpdate(prevProps, prevState) {
    this._updateLocalStorage();

    if (this.state.searchValue !== "") {
      this.setState({
        filteredNotes: this.state.notes.filter(
          note =>
            note.text
              .toLowerCase()
              .indexOf(this.state.searchValue.toLowerCase()) !== -1
        )
      });
    } else if(prevState.filteredNotes === this.state.filteredNotes) {
      //do nothing
    } else if(this.state.searchValue === "") {
      this.setState({
        filteredNotes: this.state.notes 
      });
    }
  }