I am getting this error when I run my code.
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.
And here's the code . it's referencing.
69 | }
70 |
71 | addQuestion = () => {
> 72 | this.setState({numQuestions: this.state.numQuestions + 1});
73 | }
74 |
75 | render() {
131 | <div className="field">
132 | <div className="endButtons">
133 | <button id="addQuestionButton"
> 134 | onClick={this.addQuestion()}>Add Question</button>
135 | <input
136 | type="submit"
137 | value="Submit"
5 | import App from './App';
6 | import registerServiceWorker from './registerServiceWorker';
7 |
> 8 | ReactDOM.render(<App />, document.getElementById('root'));
9 | registerServiceWorker();
10 |
11 |
I set my stuff up the way the articles on the actual React site said to and it "came" with this neat console type thing, that's where I came up with the above code. I'm very new to React, JSX, and Javascript (and just programing in general) and I don't really understand what this means so if you could also explain a little that would be awesome.
Thanks!
You are calling this.addQuestion
in your render method, which in turn calls setState
which will result in a new render, and the indefinite loop continues.
You want to give onClick
a function reference, not call it directly.
<button id="addQuestionButton" onClick={this.addQuestion}>Add Question</button>
this.addQuestion()
invoked every time the component re-renders, thus causing a loop.
Change the method this.addQuestion()
to () => this.addQuestion()
<button id="addQuestionButton" onClick={() => this.addQuestion()}>Add Question</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With