成功签入 React 后无法增加值
Cannot increment value after successful check in React
我在函数(React 事件处理程序)中有一个变量,用于计算用户给出的正确答案的数量。
函数如下:
handleFinishAssessment(event) {
event.preventDefault();
console.log("Assessment Finished");
let correctAnswers = 0;
let assessmentAnswersObjects = [];
this.state.assessmentAnswers.map(answersArray =>
answersArray.map(questionsAnswers =>
questionsAnswers.map(
questionAnswer =>
(assessmentAnswersObjects = [
...assessmentAnswersObjects,
questionAnswer,
])
)
)
);
assessmentAnswersObjects.map(assessmentAnswer =>
this.state.userAnswers.map(
answerGiven =>
answerGiven === assessmentAnswer.answer &&
assessmentAnswer.is_correct_answer &&
console.log("Correct Answer") && // it's printed the number of time the check is successful
correctAnswers++
)
);
console.log("correct answers: ", correctAnswers);
}
基本上,每次检查守卫遇到正确答案(发生)时,函数都会打印“正确答案”,并且还应该增加 correctAnswers
的值(没有发生)。
为什么会这样?
如何让这个功能发挥作用?
编辑
我认为在你的情况下,通过像下面这样链接条件,在 console.log("Correct Answer")
returns undefined
中,所以下一个条件 correctAnswers++
不会执行,删除 console.log
再检查一次
this.state.userAnswers.map(
answerGiven =>
answerGiven === assessmentAnswer.answer &&
assessmentAnswer.is_correct_answer &&
//console.log("Correct Answer") && this will return undefined and not going to execute next condition
correctAnswers++
)
我在函数(React 事件处理程序)中有一个变量,用于计算用户给出的正确答案的数量。
函数如下:
handleFinishAssessment(event) {
event.preventDefault();
console.log("Assessment Finished");
let correctAnswers = 0;
let assessmentAnswersObjects = [];
this.state.assessmentAnswers.map(answersArray =>
answersArray.map(questionsAnswers =>
questionsAnswers.map(
questionAnswer =>
(assessmentAnswersObjects = [
...assessmentAnswersObjects,
questionAnswer,
])
)
)
);
assessmentAnswersObjects.map(assessmentAnswer =>
this.state.userAnswers.map(
answerGiven =>
answerGiven === assessmentAnswer.answer &&
assessmentAnswer.is_correct_answer &&
console.log("Correct Answer") && // it's printed the number of time the check is successful
correctAnswers++
)
);
console.log("correct answers: ", correctAnswers);
}
基本上,每次检查守卫遇到正确答案(发生)时,函数都会打印“正确答案”,并且还应该增加 correctAnswers
的值(没有发生)。
为什么会这样?
如何让这个功能发挥作用?
编辑
我认为在你的情况下,通过像下面这样链接条件,在 console.log("Correct Answer")
returns undefined
中,所以下一个条件 correctAnswers++
不会执行,删除 console.log
再检查一次
this.state.userAnswers.map(
answerGiven =>
answerGiven === assessmentAnswer.answer &&
assessmentAnswer.is_correct_answer &&
//console.log("Correct Answer") && this will return undefined and not going to execute next condition
correctAnswers++
)