【问题标题】:How to fix "Maximum update depth exceeded.calls setState inside componentWillUpdate or componentDidUpdate." error in react?如何修复“超出最大更新深度。在 componentWillUpdate 或 componentDidUpdate 中调用 setState。”反应错误?
【发布时间】:2019-10-25 16:11:15
【问题描述】:

代码运行良好,但不知从何而来。

我尝试将条件切换到componentDidMount,但这也不起作用。得到这个函数的错误。

  componentDidUpdate() {
    if (
      this.props.firebase.auth.currentUser &&
      this.props.firebase.auth.currentUser.userProfile &&
      !this.state.userProfile
    ) {
      this.setState(
        {
          userProfile: this.props.firebase.auth.currentUser.userProfile
            .userProfile
        }
      );
    }
  }

它应该将用户重定向到下一个页面,但给我一个“超出最大更新深度”的错误。

【问题讨论】:

  • this.props.firebase.auth.currentUser.userProfile.userProfile,你在currentUser.userProfile里面有userProfile吗?
  • 来自文档 -> You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition 您的情况需要与prevProps.. reactjs.org/docs/react-component.html#componentdidupdate进行比较

标签: javascript reactjs firebase debugging npm


【解决方案1】:

为什么会有 .userProfile.userProfile?您可能会使用未定义的方式更新 userProfile,因此您的 !this.state.userProfile 检查失败。

我会删除第二个 .userProfile。

【讨论】:

    【解决方案2】:

    您没有将prevProps 传递给componentDidUpdate,然后在您的条件中使用它。如果没有关于您为什么使用 userProfile 的更多信息,我建议您执行以下操作:

    componentDidUpdate(prevProps){
       if(this.props.firebase.auth.currentUser === this.prevProps.firebase.auth.currentUser) {
       ///your code
    }}
    

    this.props.firebase.auth.currentUser.userProfile && !this.state.userProfile 的逻辑似乎不应该位于此方法中,因为如果您比较 currentUser 是否仍然存在并且组件更新后是否相同,这似乎是多余的。

    【讨论】:

      猜你喜欢
      • 2019-04-24
      • 2020-10-22
      • 1970-01-01
      • 2020-07-15
      • 2023-04-09
      • 2021-10-01
      • 2019-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多