![](/img/trans.png)
[英]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.