[英]How to Increment the Object inside the Array, Of Array of Object in React js?
[英]react js increment count existing object in array
我正在创建一个简单Point of sale
系统并在我的Cart reducer
中。
我需要检查object
是否已经在Cart Array
中,然后增加数量。 如果Object
不存在,则将其推入Cart Array
代码按预期工作。 但是有更好的解决方法吗?
推车减速机
export const cartReducer = (state: IState, action: Actions) => {
const { uid } = action.payload
switch (action.type) {
case 'ADD_TO_CART': {
const cart_item = state.cart.filter(item => item.uid === uid)
if (cart_item.length > 0) {
return {
...state,
cart: state.cart.map(item => item.uid === uid ? { ...item, quantity: item.quantity + 1 } : item)
}
}
return {
...state,
cart: [...state.cart, action.payload]
}
}
}
}
这对我来说看起来很合理,但你可以通过
cart
而不是两次返回some
代替filter
case 'ADD_TO_CART': {
const exists = state.cart.some(item => item.uid === uid);
const cart = exists
? state.cart.map(item => item.uid === uid ? { ...item, quantity: item.quantity + 1 } : item)
: [...state.cart, action.payload];
return {
...state,
cart
};
}
您可以简单地使用findIndex
,而不是循环遍历所有项目两次(过滤一次,映射一次)。
findIndex
优于filter
的好处:一旦条件满足,迭代就会停止,你会得到它的索引,不像 filter 循环遍历数组中的所有元素。
如果您的数组元素较少,则您的解决方案很好,但findIndex
在长 arrays 的情况下会提供更好的性能。
switch (action.type) {
case 'ADD_TO_CART': {
const cartItemIndex = state.cart.findIndex(item => item.uid === uid)
const updatedCart = [...state.cart]
if (cartItemIndex > -1) {
updatedCart[cartItemIndex] = { ...updatedCart[cartItemIndex], quantity: item.quantity + 1 }
}
else {
updatedCart.push(action.payload)
}
return {
...state,
cart: updatedCart
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.