[英]Why is one state variable updating and the other not?
I am brand new to React and I thought I was doing this correctly.我是 React 的新手,我认为我这样做是正确的。 I am trying to keep score for a trivia game I'm developing.
我正在尝试为我正在开发的问答游戏计分。 When I set state, the score is updating but the number of correct responses is not.
当我设置 state 时,分数正在更新,但正确答案的数量没有。 Interestingly, this is only the case when I deploy the site to firebase, it works as expected when served locally.
有趣的是,只有当我将站点部署到 firebase 时才会出现这种情况,它在本地服务时按预期工作。
This function is in the parent game component.这个 function 在父游戏组件中。 this.state.points is incrementing, this.state.numberCorrect/Incorrect is not.
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);
}
This is the function called in the child component which is displaying the question.这是在显示问题的子组件中调用的 function。
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);
}
}
Ciao, I think the problem is on childSubmitAnswer
function. Try to modify it like that:再见,我认为问题出在
childSubmitAnswer
function 上。尝试这样修改它:
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);
}
Explanation: in Javascript when you use ++ after the operand, the value will be returned before the operand is increased.说明:Javascript 操作数后加++,返回操作数递增前的值。 Example:
例子:
let a = 0;
console.log(a++); // shows 0
console.log(a); // shows 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.