为什么我使用componentWillReceiveProps收到此错误? [英] Why I receive this error using componentWillReceiveProps?

查看:90
本文介绍了为什么我使用componentWillReceiveProps收到此错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Receive error: × Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

试图删除带有错误和setState的零件(因为它看起来像是无限循环的原因).没有帮助

Tried to delete part with error and setState (because it looks like the reason of infinite loop). Didn't help

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

推荐答案

history.push导致重新渲染,它调用componentWillReceiveProps,一切都循环进行.

history.push causes a rerender, it calls componentWillReceiveProps and everything goes in a loop.

改为使用此代码:

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

如果您在其他地方遇到类似的错误,这仍然可能导致循环.

This can still cause a loop if you have a similar mistake somewhere else.

这篇关于为什么我使用componentWillReceiveProps收到此错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆