我正在学习反应,我有这个教程在线测验 - 反应,所以我尝试做一些调整,我希望用户点击HellYa它会增加例如答案类型 - “布朗”“D”“JP”每个按+1,这是我的quizQuestion.js
{
question: "I am task oriented in order to achieve certain goals",
answers: [
{
type: "Brown,D,JP",
content: "Hell Ya!"
},
{
type: " ",
content: "Nah"
}
]
},
我的init状态构造函数如下
this.state = {
counter: 0,
questionId: 1,
question: '',
answerOptions: [],
answer: '',
answersCount: {
Green: 0,
Brown: 0,
Blue: 0,
Red: 0,
A: 0,
B: 0,
C: 0,
D: 0,
EI: 0,
SN: 0,
TF: 0,
JP: 0
},
result: ''
};
并按照教程,我使用react-addons-update来更新answerCount并回答,这是我的函数
setUserAnswer(answer) {
if (answer.trim()) {
const answer_array = answer.split(',');
let updatedAnswersCount = null;
answer_array.forEach((answer) => {
updatedAnswersCount = update(this.state.answersCount, {
[answer]: {$apply: (currentValue) => currentValue + 1}
});
}, this);
this.setState({
answersCount: updatedAnswersCount,
answer: answer
});
}
}
但经过多次尝试后,我仍然无法弄清楚如何将答案类型单独增加1,现在它只更新JP +,但它不会更新Brown和D,我该怎么办?感谢
答案 0 :(得分:1)
似乎总是使用当前状态作为基础对象,因此只更新foreach中的最后一个答案。
尝试以下方法:
setUserAnswer(answer) {
if (answer.trim()) {
const answer_array = answer.split(',');
let answerCountUpdates = update(this.state.answersCount, {$merge: {}}) // copy this.state.answersCount, will search a better way
answer_array.forEach((answer) => {
answerCountUpdates = update(answerCountUpdates, {
[answer]: {$apply: (currentValue) => currentValue + 1}
});
}, this);
updatedAnswersCount = update(this.state.answersCount, {$merge: answerCountUpdates})
this.setState({
answersCount: updatedAnswersCount,
answer: answer
});
}
}
答案 1 :(得分:0)
看起来您已将forEach()
的迭代对象命名为“answer”以及传递给setUserAnswer()
的参数。尝试更改其中一个,因为它可能会导致问题。