[英]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.