Javascript 如何在React中更新数组内对象中键的值?
我有一个用户添加的动态项目列表。我希望在用户添加列表中已存在的项目时避免重复。我的清单看起来像Javascript 如何在React中更新数组内对象中键的值?,javascript,reactjs,Javascript,Reactjs,我有一个用户添加的动态项目列表。我希望在用户添加列表中已存在的项目时避免重复。我的清单看起来像 itemList = [ {itemId:1, name:"x", quantity:5}, {itemId:4, name:"y", quantity:2}] 因此,现在如果用户添加数量为2的项目x,我希望具有项目x的对象将数量更新为7,而不是添加一个全新的对象。 我使用find()方法获取已经存在的项并将其存储到变量中,itemObj是用户最近添加的项 l
itemList = [ {itemId:1, name:"x", quantity:5}, {itemId:4, name:"y", quantity:2}]
因此,现在如果用户添加数量为2的项目x,我希望具有项目x的对象将数量更新为7,而不是添加一个全新的对象。
我使用find()方法获取已经存在的项并将其存储到变量中,itemObj是用户最近添加的项
let alrItem = state.itemList.find(
(e) => e.itemId === itemObj.itemId
);
let newItem = alrItem;
newItem.quantity += itemObj.quantity;
如何将此新项目合并到itemList,以便它只更新该特定项目的数量?您要做的是在
itemList
数组中查找对象,然后直接改变状态。国家不应该直接变异
不要使用.find()
方法,而是使用.map()
方法迭代数组并更新与新项目id匹配的项目数量
let updatedItemList = state.itemList.map((item) => {
if (item.itemId === itemObj.itemId) {
return { ...item, quantity: item.quantity + itemObj.quantity };
}
return item;
});
// update the state
setItemList(updatedItemList);
请注意,如果项目未出现在项目列表中,则上述代码不会执行任何操作。理想情况下,您还应该处理新项目尚未出现在项目列表中的情况。在这种情况下,只需在项目列表中添加新项目即可
要处理这种情况,您只需要一个额外的变量,该变量可用于了解.map()
方法中的if
条件是否为true
let exists = false;
let updatedItemList = state.itemList.map((item) => {
if (item.itemId === itemObj.itemId) {
exists = true;
return { ...item, quantity: item.quantity + itemObj.quantity };
}
return item;
});
// if the item isn't present in the list, add it in the "updatedItemList"
if (!exists) {
updatedItemList.push(itemObj);
}
// update the state
setItemList(updatedItemList);
输出:
itemList:[{“itemId”:1,“name”:“x”,“quantity”:7},{“itemId”:4,“name”:“y”,“quantity”:2}]您的代码已经这样做了。也许你应该添加一个解释你到底被困在哪里的变量。如果你这样做,你不需要“合并”任何东西,因为你正在变异数组中已经存在的同一个对象。但是,像这样直接改变状态是不正确的,因为React看不到数组已更改(因为引用时它是相同的),因此您不会得到重新加载程序。虽然这是正确的方法,但请注意,如果该项不在列表中,这将不会更新任何内容。我的理解是,在这种情况下,OP希望将其与数量一起添加到列表中。@RobinZigmond感谢您提醒我注意这一点。更新了答案以处理该案例。
let itemList = [ {itemId:1, name:"x", quantity:5}, {itemId:4, name:"y", quantity:2}]
let itemObj = {itemId:1, name:"x", quantity:2}
const target = itemList.find(element =>
element.itemId === itemObj.itemId
);
if (target) {
target.quantity = target.quantity + itemObj.quantity;
} else {
itemList.push(itemObj);
}
console.log('itemList: ' + JSON.stringify(itemList));