react js useState更新数量



我是新手。我在更新数量时遇到问题。

const[persons,setPersons] = useState(personLists)

如果您使用console.log(persons),它将给出如下输出。现在我想更新特定人索引的特定杂项索引的数量。下面的数组中有两个人,每个人都有另外两个misc数组


[
{
id: 1,
name: "john",
gender: "m",
misc: [
{
id: 1,
name: "xxx",
qty: 1
},
{
id: 2,
name: "xxx1",
qty: 1
}
]
},
{
id: 2,
name: "mary",
gender: "f",
misc: [
{
id: 1,
name: "aaa",
qty: 1
},
{
id: 2,
name: "bbb",
qty: 1
}
]
},
]

现在我想为那个特定的人在misc数组下更新qty。我有一个函数,取person数组的索引和misc数组的索引,如下所示。

const updatePersonMiscQty = (personIndex, miscIndex) => {

setPersons(persons =>
persons.map((person,key) => {
const found = person.misc.find(d => key === miscIndex);
if (found) {
found.qty += 1;
}
return person;
})

}

假设我的personIndex为0,miscIndex=为1所以当我们点击按钮时,它应该查看第一人称数组,转到misc的第二索引并更新数量。

我正在寻找一个解决方案

按索引访问条目并更新

setPersons(persons => {
const miscItem = persons[personIndex]?.misc?.[miscIndex]
if (miscItem ) {
miscItem.qty += 1;
}
return [...persons];
}
})

最新更新