有一个反应问卷组件,可以将选定的答案添加到this.state = { answer: []}
,效果很好。在用户更新应答的同时,将其添加为另一个对象。当 questionID 相同时,是否有任何选项可以更新setState
中的对象?
onChange(event) {
const field = event.target.name;
let question = event.target.dataset.questionId;
let result = event.target.value;
let answer = {
'questionID': question,
'answerValues': result
};
this.setState({
answer: [
...this.state.answer,
answer,
]
});
console.log(this.state.answer);
}

目前同样的问题就像这样添加
[
{
"questionID": 1,
"answerValues": 2
},
{
"questionID": 2,
"answerValues": 5
}
{
"questionID": 1,
"answerValues": 1
}
]
更新对象的任何解决方案如果已经存在questionID
this.state.answer
,那么
答案 0 :(得分:1)
您需要使用对象分配,在此代码中,您将能够更新问题,如果它已经存在于ID中,否则它将添加新问题
const field = event.target.name;
let question = event.target.dataset.questionId;
let result = event.target.value;
let newAnswer = {
'questionID': question,
'answerValues': result
};
this.setState(prevState => {
const user = prevState.answer.find(d => d.questionID === newAnswer.questionID);
if (!!user) {
Object.assign(user, newAnswer);
const data = prevState.answer.map(d => d.questionID === user.questionID ? user : d);
return { answer: data }
} else {
return { answer: prevState.answer.concat(newAnswer)};
}
})
答案 1 :(得分:1)
let questionExistsInState = (this.state.answer.some((ans) => (ans.questionId === answer.questionId)));
let newState = []
if(questionExistsInState) {
newState = this.state.answer.map((ans) => (ans.questionId === answer.questionId ? answer : ans))
} else {
newState = [answer, ...this.state.answer]
}
this.setState({
answer: newState ,
});
此外,我发现您在onChange事件中使用了setState。请注意,setState不是同步操作,如果您在setState()调用后立即进行控制台日志记录,则不会保证您将看到新状态。您可以控制登录setState函数的回调(第二个参数)。
答案 2 :(得分:1)
我建议将答案存储为一个对象,其中键是问题ID,值是答案。在你的构造函数中:
this.state = { answer: {}}
然后在onChange()
:
this.setState({
answer: Object.assign({}, this.state.answer, {
[question]: result,
});
});
答案 3 :(得分:0)
你可以这样减少:
this.setState({
answer: this.state.answer.reduce((acc,ans)=>{
return ans.questionID === answer.questionID
? [...acc,answer]
: [...acc,ans]
},[])
})
答案 4 :(得分:0)
你可以像使用数组map
那样做this.setState({
answer: this.state.answer.map(
(existingAnswer) => (existingAnswer.questionID === answer.questionID
? answer : existingAnswer)),
});