为什么一个状态变量更新而另一个不更新?

时间:2020-07-17 21:52:56

标签: javascript reactjs firebase

我是React的新手,我认为自己做得正确。我正在努力为正在开发的琐事游戏保持得分。当我设置状态时,分数会更新,但正确答案的数量不会更新。有趣的是,只有在将网站部署到Firebase时才如此,当在本地提供服务时,它可以按预期工作。

此功能在父游戏组件中。 this.state.points正在增加,this.state.numberCorrect / Incorrect不是。

childSubmitAnswer(dataFromChild) {
  if (dataFromChild.correct === true) {
    this.setState((prevState) => {
      return {
        numberCorrect: prevState.numberCorrect++,
        points: prevState.points + dataFromChild.points
      }
    });
  } else {
    this.setState((prevState) => {
      return {
        numberIncorrect: prevState.numberIncorrect++,
        points: prevState.points - dataFromChild.points
      }
    });
  }
  console.log(this.state.numberCorrect);
}

这是在显示问题的子组件中调用的函数。

handleSubmit(event) {
  event.preventDefault();
  let verification = new AnswerVerification();
  this.answerSubmitted();
  if (verification.verifyAnswer(this.state.submissionValue, this.state.answer)) {
    let data = {
      correct: true,
      points: this.props.points
    }
    this.props.childSubmitAnswer(data);
  } else {
    let data = {
      correct: false,
      points: this.props.points
    }
    this.props.childSubmitAnswer(data);
  }
}

1 个答案:

答案 0 :(得分:-1)

Ciao,我认为问题出在childSubmitAnswer函数上。尝试像这样修改它:

childSubmitAnswer(dataFromChild) {
  if (dataFromChild.correct === true) {
  this.setState((prevState) => {
  return {
    numberCorrect: prevState.numberCorrect + 1,
    points: prevState.points + dataFromChild.points
  }
});
} else {
  this.setState((prevState) => {
    return {
      numberIncorrect: prevState.numberIncorrect + 1,
      points: prevState.points - dataFromChild.points
    }
  });
}
console.log(this.state.numberCorrect);
}

说明:在Javascript中,当在操作数之后使用++时,将在增加操作数之前返回该值。示例:

let a = 0;
console.log(a++); // shows 0
console.log(a);   // shows 1