状态未在React中更新

时间:2020-04-08 05:38:39

标签: javascript reactjs setstate

我正在YouTube上关注有关React版本16测验应用程序的教程。状态和函数中有一些变量是借助setState更新的。变量的值未更新。下面的函数正在更新这些变量。正在从componentDidMount函数中调用此函数。

displayQusetions = (questions = this.state.questions, currentQuestion, nextQuestion, previousQustion) => {
   let { currentQuestionIndex } = this.state;
   if (!isEmpty(this.state.questions)) {
      questions = this.state.questions;
      currentQuestion = questions[currentQuestionIndex];
      nextQuestion = questions[currentQuestionIndex + 1];
      previousQustion = questions[currentQuestionIndex - 1];
      const answer = currentQuestion.answer;

      this.setState({
         currentQuestion,
         nextQuestion,
         previousQustion,
         answer
      })

      console.log(this.state.currentQuestion);
      console.log(this.state.nextQuestion);
      console.log(this.state.previousQustion);
      console.log(this.state.answer);
   }
}

我是新来的反应者。请帮忙。

1 个答案:

答案 0 :(得分:0)

您可以在回调

中查看状态更新值
this.setState({
                currentQuestion,
                nextQuestion,
                previousQustion,
                answer
            },()=>{
            console.log(this.state.currentQuestion);
            console.log(this.state.nextQuestion);
            console.log(this.state.previousQustion);
            console.log(this.state.answer);

})