我的反应状态如下:
{
questionno: 1,
questionListData: [
{
id:1,
question:'which continent India belongs to?',
options:[{opt:'Australia'},{opt:'Europe'},{opt:'Asia'},{opt:'Africa'}]
}
{
id:2,
question:'New delhi is capital of which country?',
options:[{opt:'India'},{opt:'Croatia'},{opt:'Sri Lanka'},{opt:'Latvia'}]
}
]
}
我要在单击按钮时调用一个函数,该函数会更新我对现有选项所做的所有更改。在此onClick函数中,我做了这样的事情:
this.setState(prevState => ({
...prevState,
questionListData: [
...prevState.questionListData,
...prevState.questionListData.map((q, z) => {
// checks the current question number where i made the change in options
if(z === this.state.questionno-1) {
q.options.map((g, b) => {
// this is the changed value is stored somewhere on change
console.log('dataFromChild[`op_${b}`]: ', dataFromChild[`op_${b}`]);
g.opt = dataFromChild[`op_${b}`];
});
}
// here IS the problem, i also tried return g, but same result
return {...{}}
// this.setState({questionListData: [...this.state.questionListData.slice(0, 3), updatedImage, ...this.state.images.slice(4)]})
})
]
}), () => {
console.log('hi22:', this.state)
});
所以问题在于,尽管我正在状态选项数组中更新存储值,但是可能由于{}
而在questionListData
上添加了额外的return {...{}}
。我还尝试了return g,但是随后它添加了已经添加的值(按预期方式)。所以我只希望更改能够在特定选项上更新(正在发生),但是在状态上附加的更多内容是我所不想要的。请帮忙。
答案 0 :(得分:0)
您需要在map
中返回修改后的对象,并删除多余的...prevState.questionListData
,因为基本上是在同一数组上进行复制:
this.setState(prevState => ({
...prevState,
questionListData: prevState.questionListData.map((q, z) => {
if (z === this.state.questionno - 1) {
q.options = q.options.map((g, b) => {
// this is the changed value is stored somewhere on change
console.log('dataFromChild[`op_${b}`]: ', dataFromChild[`op_${b}`]);
g.opt = dataFromChild[`op_${b}`];
return g; // Return the object here
});
}
return q; // And here
})
}), () => console.log('hi22:', this.state));