ReactJS onClick state change one step behind

后端 未结 2 1718
孤城傲影
孤城傲影 2021-01-06 04:45

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

2条回答
  •  一整个雨季
    2021-01-06 05:20

    setState() is not necessarily a synchronous operation:

    setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state aft

    There is no guarantee of synchronous operation of calls to setState and 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)
    })
    

提交回复
热议问题