代码之家  ›  专栏  ›  技术社区  ›  Ramazan Chasygov

超过最大调用堆栈大小React Redux

  •  3
  • Ramazan Chasygov  · 技术社区  · 9 年前

    maximum call stack size exceeded .也许我理解错了 componentDidUpdate ,但它不应该运行一次,而应该运行1000次。如何修复它?

    class App extends Component {
    
      constructor(props) {
        super(props);
        this.state = {
          amount: 0
        }
      }
    
      updateAmout() {
        let number = 0;
        this.props.comments.map((comment, index) => {
    
          if (comment.replyTo === null) {
    
            number += 1;
            this.setState({amount: number});
          }
          return null;
        });
      }
    
      componentWillMount() {
        this.updateAmout();
      }
    
      componentDidUpdate() {
        this.updateAmout();
      }
    
      render() {
        console.log(this.state.amount);
        return (
          <div className="comments-container">
            <div id="comments">
              <AddComment />
              <div className="comments-flow">
                <div className="comments-header">
                  <div className="pull-right">
                    <a href="" className="text-muted">Best</a> |
                    <a href="" className="active">Newest</a> |
                    <a href="" className="text-muted">Oldest</a>
                  </div>
                  <b>6 Comments</b>
                </div>
                <RenderComments />
              </div>
              <button className="btn btn-block">More...</button>
            </div>
          </div>
    
        ) // return
      } // render
    } // App
    2 回复  |  直到 9 年前
        1
  •  6
  •   Dez    9 年前

    每次在中修改状态时 componentDidUpdate ,异步抛出重新渲染。 updateAmount ,您正在修改状态。 您正在调用该方法 ,因此您启动了一个无限的重新渲染循环,因此创建的这个无限循环最终会浪费javascript内存。

    更新状态时的反应周期如下。所以你很容易理解为什么你会进入一个无尽的循环。 enter image description here

        2
  •  1
  •   Has    8 年前

    我找到了问题的答案。我需要使用 nextProps 论元与方法 componentWillUpdate 而不是 componentDidUpdate 方法

    // before
    componentDidUpdate() {
     this.updateAmout();
    }
    
    // after
    componentWillUpdate(nextProps) {
      if (!_.isEqual(this.props, nextProps)) {
        this.updateAmout();
      }
    }