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

时间:2017-07-10 22:10:43

标签: javascript reactjs redux react-redux

我有错误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 个答案:

答案 0 :(得分:6)

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

更新状态时的React循环如下。因此,您可以轻松理解为什么要进入无限循环。 enter image description here

答案 1 :(得分:0)

我找到了问题的答案。我需要使用git参数和方法nextProps而不是componentWillUpdate方法。

componentDidUpdate