【问题标题】:Uncaught RangeError: Maximum call stack size exceeded in React未捕获的 RangeError:React 中超出了最大调用堆栈大小
【发布时间】:2017-11-08 22:11:52
【问题描述】:

我收到了

错误:“未捕获的 RangeError:超出最大调用堆栈大小”

我怀疑我的 componentWillUpdate 方法中的这段代码是原因,因为我只是在添加代码后才收到错误。我在这里做错了什么吗?

componentWillUpdate(nextProps, nextState) {

...

if (nextProps.show) {
  for (var i = 0; i < this.props.data.actions.length; i++) {
    if (this.props.data.actions[i].assignedTo !== this.state.userId && this.state.showActions === true) {
      this.setState({ showActions: false })
    }
    if (this.props.data.actions[i].assignedTo === this.state.userId && this.state.showActions === false) {
      this.setState({ showActions: true })
    }
  }
 }

...

}

nextProps.show 在单击按钮时设置为 true,然后检查分配操作的人员是否与登录的用户相同,然后将状态 showActions 设置为 true。此状态用于在满足代码中的条件时显示/隐藏行

【问题讨论】:

  • 这意味着在您的代码中的某个地方,您正在调用一个函数,该函数又调用另一个函数,依此类推,直到您达到调用堆栈限制。如所述stackoverflow.com/questions/6095530/…

标签: javascript reactjs


【解决方案1】:

由于你设置了state,这将再次调用componentWillUpdate,因此这个递归调用是堆栈超出的原因。

componentWillMount() 不同,我们不应该在componentWillUpdate() 中调用this.setState()。我们不调用this.setState() 的原因是该方法触发了另一个componentWillUpdate()。如果我们在componentWillUpdate() 中触发状态更改,我们将陷入无限循环。

【讨论】:

    【解决方案2】:

    this.state 尚未在 componentWillUpdate 中发生变异。

    作为reuslt,使用nextState而不是this.state来验证使用this.setState后的值是否正常:

    componentWillUpdate(nextProps, nextState) {
    
    ...
    
    if (nextProps.show) {
      for (var i = 0; i < this.props.data.actions.length; i++) {
        if (this.props.data.actions[i].assignedTo !== this.state.userId && nextState.showActions === true) {
          this.setState({ showActions: false })
        }
        if (this.props.data.actions[i].assignedTo === this.state.userId && nextState.showActions === false) {
          this.setState({ showActions: true })
        }
      }
     }
    
    ...
    
    }
    

    【讨论】:

      【解决方案3】:

      根据React componentWillUpdate docs

      注意这里不能调用 this.setState();你也不应该这样做 任何其他会触发 在 componentWillUpdate() 返回之前更新到 React 组件。如果 您需要更新状态以响应道具更改,使用 componentWillReceiveProps() 代替。

      您应该将您的代码移至componentWillReceiveProps 方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-22
        • 1970-01-01
        • 2013-05-04
        • 2020-10-02
        • 2012-06-17
        • 2018-02-28
        • 2017-04-12
        • 2014-08-01
        相关资源
        最近更新 更多