[英]How to update nested object having array with useState in Reactjs?
你好开发者你好吗?
我正在尝试更新嵌套值,但都失败了。
const [ControlGaps, setControlGaps] = useState([
{
id: 1,
name: "Pizza 1",
status: 1,
applicable: true,
questions: [
{
id: 1,
question:
"how are you?",
answer: null,
evidence: null,
treatment: null,
type: "Implemented",
{
id: 2,
evidence: null,
treatment: null,
type: "Implemented",
question:
"how old are you?",
answer: null,
}
],
},
{
id: 2,
name: "Pizza 2",
status: 1,
applicable: true,
questions: [
{
id: 1,
type: "Implemented",
question:
"How are you 2?",
answer: null,
evidence: null,
treatment: null,
{
id: 2,
answer: null,
evidence: null,
treatment: null,
type: "Implemented",
question:
"How old are you?",
},
],
}])
我尝试使用 onChange 这个
setControlGaps([...ControlGaps, [ControlGaps[index]].applicable]:checked]);
或者
setControlGaps({
...ControlGaps,
[ControlGaps[index].applicable]: checked,
});
但一切都错了。
问题是如何更新嵌套字段中的值,例如更新对象数组中 object 中的字段。
可以使用一些slice()
和spread
来完成。 但是您应该查看此类嵌套内容的不变性助手。
setControlGaps([setControlGaps.slice(0,index),
{ ...ControlGaps[index],
applicable : checked
}
,setControlGaps.slice(index+1)]);
尝试这个
setControlGaps(prevState => {
const newState = prevState.map((item, itemIndex) => {
if (itemIndex === index) {
item.applicable = false;
return item;
}
return item;
});
return newState;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.