[英]Iterate a property of Object in Array that Matches Query
我正在 React 中工作,并希望根据它是否与按下“迭代”按钮的项目匹配来迭代“购物车”数组中对象的“数量”属性。
我原来的解决方案是这样的......
setCart((cart) => {
const itemMatch = cart.find((cartItem) => cartItem.name === item.name);
if (itemMatch !== undefined) {
itemMatch.amount = itemMatch.amount + 1;
} else {
cart.push(item);
}
return [...cart];
})
但是,迭代是按 2 计数的。
我的第二个解决方案是...
setCart((cart) => {
const updatedCart = cart.map((cartItem) => {
if (cartItem.name === item.name) {
return {...cartItem, amount: cartItem.amount + item.amount}
} else {
return cartItem
}
})
return updatedCart;
})
此解决方案有效,但我无法弄清楚这两者之间的区别是什么。 如果有人可以帮助解释真正有助于我理解的差异。 谢谢。
在第一个解决方案中,您将项目推送到已经拥有所有这些项目的现有数组中。
offtop :第二个解决方案在不改变现有数据方面也更好。
在这里,您正在做不同的事情。
假设您有一个这样的示例输入:
const item = { name: "abc", amount: 5 }
const cart = [
{ name: "ab", amount: 15 },
{ name: "def", amount: 10 }
]
在场景 1 中:
const setCart = ((cart) => {
/* first finding if the object which are already exist in cart array
is also exist in item object or not. */
const itemMatch = cart.find((cartItem) => cartItem.name === item.name);
// if item found increase amount by 1
if (itemMatch !== undefined) {
itemMatch.amount = itemMatch.amount + 1;
} else { // if item not found add that item to array
cart.push(item);
}
// and returning it
return [...cart];
})
// output
/* [
{ name: 'ab', amount: 15 },
{ name: 'def', amount: 10 },
{ name: 'abc', amount: 5 }
] */
在场景 2 中:
const setCart = ((cart) => {
// looping into the cart array and searching if item exist in cart or not
const updatedCart = cart.map((cartItem) => {
// if item which are in cart is also exist
if (cartItem.name === item.name) {
// return all oder cart item, and update the amount
return {...cartItem, amount: cartItem.amount + item.amount }
} else {
// return the cart item as it is
return cartItem
}
})
// returning the cart array
return updatedCart;
})
// output
/* [
{ name: 'ab', amount: 15 },
{ name: 'def', amount: 10 }
] */
在场景 2 中,
您永远无法将新项目添加到购物车中,因为您正在循环进入购物车项目并检查项目是否存在(如果存在则更新购物车,如果不存在则按原样返回购物车项目)。
在场景 1 中,
您首先要查找购物车项目是否存在,并确保该项目是否已存在于购物车中,只需更新数量,如果不存在则将项目添加到购物车。 (这在真实场景中有效)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.