Maximum call stack size exceeded React-Redux

Viewed 8072

I have error maximum call stack size exceeded. Maybe I in wrong way understand componentDidUpdate, but shouldn't it's run one time, instead 1000. How fix it?

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 Answers

I found the answer to my question. I need to use the nextProps argument and the method componentWillUpdate instead of the componentDidUpdate method.

// before
componentDidUpdate() {
 this.updateAmout();
}

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

Related