[英]Update object across array of objects using setState
My question relates to this one but the issue here that I must relay on object properties and I want to update just ONE object. If I am using map
it updates all objects in my array of objects.我的问题与此有关,但这里的问题是我必须中继 object 属性,我只想更新一个 object。如果我使用
map
,它会更新我的对象数组中的所有对象。 Its structure is:它的结构是:
[
{
id: 1,
itemNames: ['aaa','xxx'],
removed: [],
...
},
{
id: 1,
itemNames: ['yyy', 'xxx'],
removed: [],
...
},
...
]
My logic is: I look for item name across itemNames, if it exists in state - remove it from first object occurance and add it to removed property of this object. I managed to do it with map, but then it does it for every object that has given item name.我的逻辑是:我在 itemNames 中查找项目名称,如果它存在于 state 中 - 从第一次出现的 object 中删除它,并将其添加到此 object 的已删除属性中。我设法用 map 完成了它,但随后它对每 object 进行了一次已给出项目名称。
function filterByItemName(itemName) {
this.setState(prevState => ({
...prevState,
arr: prevState.arr.map(item) => {
if (item.itemNames.includes(itemName)) {
return {
...item,
removed: [...item.removed, itemName],
itemNames: removeFirstFoundElement(item.itemNames, itemName),
};
}
return item;
}),
}));
}
The following code works in a way that it finds ALL objects with given itemName - but I would like to change just first case... After calling filterByItemName('xxx')
I want it to be:以下代码的工作方式是找到具有给定 itemName 的所有对象 - 但我只想更改第一种情况......调用
filterByItemName('xxx')
后我希望它是:
[
{
id: 1,
itemNames: ['aaa'],
removed: ['xxx],
...
},
{
id: 1,
itemNames: ['yyy', 'xxx'],
removed: [],
...
},
...
]
While now it is as follows:而现在它是这样的:
[
{
id: 1,
itemNames: ['aaa'],
removed: ['xxx],
...
},
{
id: 1,
itemNames: ['yyy'],
removed: ['xxx'],
...
},
...
]
I think you can set a shouldInsert
flag to check if you've already inserted once or not.我想你可以设置一个
shouldInsert
标志来检查你是否已经插入过一次。 Here is my approach.这是我的方法。 It would be easier if you could share some
codesandbox
link here.如果您可以在此处共享一些
codesandbox
链接,那就更容易了。
function filterByItemName(itemName) {
let shouldInsert = true;
this.setState(prevState => ({
...prevState,
arr: prevState.arr.map(item) => {
const found = item.itemNames.includes(itemName);
if (found && shouldInsert) {
shouldInsert = false;
return {
...item,
removed: [...item.removed, itemName],
itemNames: removeFirstFoundElement(item.itemNames, itemName),
};
}
return item;
}),
}));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.