[英]Update value in nested object in React useState
I have this useState:我有这个useState:
const [data, setData] = useState([
{
id: 1,
options: [{ id: 1, amount: 0 }, { id: 2, amount: 0 }]
},
{
id: 2,
options: [{ id: 1, amount: 0 }, { id: 2, amount: 0 }]
}
]);
so I need a function to update the option X from item X.所以我需要一个 function 从项目 X 更新选项 X。
Like this:像这样:
const increase = (itemId, optionId) => {
//setData(...)
}
I tried doing something like this:我试着做这样的事情:
const increase = (itemId, optionId) => {
const copy = [...data];
const dataItem = copy.find((item) => item.id === itemId);
const option = dataItem.options.find((item) => item.id === optionId);
option.amount = option.amount + 1;
setData(copy);
}
But it increases by two...但它增加了两个...
try this尝试这个
setData((prevArr) => {
return prevArr.map((item) => {
if (item.id !== itemId) return item;
const updOptions = item.options.map((opt) => (
opt.id === optionId ? {
...option,
amount: option.amount+1,
} : option
)
return {
...item,
options: updOptions,
}
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.