【问题标题】:Why I receive this error using componentWillReceiveProps?为什么我使用 componentWillReceiveProps 收到此错误?
【发布时间】:2019-03-25 18:09:20
【问题描述】:

接收错误:× 超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制了嵌套更新的数量以防止无限循环。

尝试删除有错误和 setState 的部分(因为它看起来像无限循环的原因)。没有帮助

componentWillReceiveProps(nextProps){
    if(nextProps.auth.isAuthenticated){
        this.props.history.push('/dashboard')
    }
    // if(nextProps.errors){
    //     this.setState({
    //         errors: nextProps.errors
    //     })
    //     console.log('Error');
    // }
};

【问题讨论】:

  • 看起来这不是导致错误的原因,能否请您发布此组件的其余代码?

标签: javascript reactjs react-router infinite-loop


【解决方案1】:

history.push 导致重新渲染,它调用componentWillReceiveProps 并且一切都在循环中。

改用此代码:

componentDidUpdate(prevProps) {
  if (
      this.props.auth.isAuthenticated
      && this.props.auth.isAuthenticated !== prevProps.auth.isAuthenticated
  ) {
    this.props.history.push('/dashboard')
  }
}

如果您在其他地方遇到类似错误,这仍然会导致循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-13
    • 2018-06-22
    • 2016-01-01
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多