我有一个对象初始状态如下:
answersCount: {
Colors: {
Green: 0,
Brown: 0,
Blue: 0,
Red: 0
},
Letters: {
A: 0,
B: 0,
C: 0,
D: 0,
},
Briggs: {
EI: 0,
SN: 0,
TF: 0,
JP: 0
}
},
我有一个setUserAnswer函数如下:
setUserAnswer(answer) {
if(answer.trim()) {
const answer_array = answer.split(',');
let updatedAnswersCount = null;
const answersCount = this.state.answersCount;
// copy this.state.answersCount
let answerCountUpdates = update(answersCount, {$merge: {}});
answer_array.forEach((answer) => {
answerCountUpdates = update(answerCountUpdates, {
[answer]: {$apply: (currentValue) => currentValue + 1}
});
}, this);
updatedAnswersCount = update(answersCount, {$merge: answerCountUpdates})
this.setState({
answersCount: updatedAnswersCount,
answer: answer
});
}
}
我使用$ apply更新值使用react-addons-update,此setUserAnswer函数将根据用户选择设置答案并将该值递增+1
问题是,在用户点击HellYa按钮后,我想让我的结果看起来像这样:
answersCount: {
Colors: {
Green: 0,
Brown: 1,
Blue: 0,
Red: 0
},
Letters: {
A: 0,
B: 0,
C: 0,
D: 1,
},
Briggs: {
EI: 0,
SN: 0,
TF: 0,
JP: 1
}
},
但现在它的唯一输出就是这样:
answersCount: {
Colors: {
Green: 0,
Brown: 0,
Blue: 0,
Red: 0
},
Brown: null
Letters: {
A: 0,
B: 0,
C: 0,
D: 0,
},
D: null
JP: null
Briggs: {
EI: 0,
SN: 0,
TF: 0,
JP: 0
}
},
如果有帮助我有问题和答案的quizQuestion.js,例如:
{
question: "I am task oriented in order to achieve certain goals",
answers: [
{
// briggs, color, letter
type: "JP,Brown,D",
content: "Hell Ya!"
},
{
type: " ",
content: "Nah"
}
]
}
答案 0 :(得分:1)
如何采取不同的方法,如此......
let answersCount = {
colors: {
Green: 0,
Brown: 0,
Blue: 0,
Red: 0
},
letters: {
A: 0,
B: 0,
C: 0,
D: 0,
},
briggs: {
EI: 0,
SN: 0,
TF: 0,
JP: 0
}
};
let applyAnswer = (answer) => {
// example answer = "JP,Brown,D"
let answerArr = answer.split(',');
let briggsAnswer = answerArr[0];
let colorsAnswer = answerArr[1];
let lettersAnswer = answerArr[2];
answersCount['briggs'][briggsAnswer] += 1;
answersCount['colors'][colorsAnswer] += 1;
answersCount['letters'][lettersAnswer] += 1;
return answersCount;
}
然后每当你得到一个" Hell Ya"时,你只需用你的答案字符串调用applyAnswer()
函数就好......
applyAnswer('JP,Brown,D');
更新:我刚才意识到,既然我们还在使用ES6,我们可以通过解构参数来清理它。
let applyAnswer = (answer) => {
// example answer = "JP,Brown,D"
const [ briggsAnswer, colorsAnswer, lettersAnswer ] = answer.split(',');
answersCount['briggs'][briggsAnswer] += 1;
answersCount['colors'][colorsAnswer] += 1;
answersCount['letters'][lettersAnswer] += 1;
return answersCount;
}