I\'m building a very primitive quiz app with ReactJS and I\'m having trouble updating the state of my Questions component. Its behavior is it renders the correc
As Sandwichz says, if you access the state right after using setState, you have no guarantee of the actual value. You could do something like this:
handleContinue() {
if (this.state.questionNumber > 3) {
this.props.unMount()
} else {
const newQuestionNumber = this.state.questionNumber + 1
this.setState({
questionNumber: newQuestionNumber
})
this.props.changeHeader("Question " + newQuestionNumber)
}
}
setState() is not necessarily a synchronous operation:
setState()does not immediately mutatethis.statebut creates a pending state transition. Accessingthis.stateaftThere is no guarantee of synchronous operation of calls to
setStateand calls may be batched for performance gains.
For this reason, this.state.questionNumber may still hold the previous value here:
this.props.changeHeader("Question " + this.state.questionNumber)
Instead, use the callback function that is called once the state transition is complete:
this.setState({
questionNumber: this.state.questionNumber + 1
}, () => {
this.props.changeHeader("Question " + this.state.questionNumber)
})