ReactJS onClick state change one step behind

后端 未结 2 1742
孤城傲影
孤城傲影 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:11

    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)
      }
    }
    

提交回复
热议问题