【问题标题】:The state is not updating in React [duplicate]React 中的状态未更新 [重复]
【发布时间】:2020-07-20 11:14:15
【问题描述】:

我正在关注 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);
   }
}

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

【问题讨论】:

标签: javascript reactjs setstate


【解决方案1】:

您可以在回调

中查看状态更新值
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);

})

【讨论】:

    猜你喜欢
    • 2015-06-11
    • 1970-01-01
    • 2021-08-24
    • 2019-08-08
    • 2019-05-30
    • 2021-07-30
    • 2020-10-26
    • 2017-01-19
    • 1970-01-01
    相关资源
    最近更新 更多