簡體   English   中英

反應js增量計數數組中現有的object

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM