簡體   English   中英

將不同尺寸的相同產品添加到購物車

[英]Add same product with different sizes to the cart

我可以添加不同的產品作為單獨的數組,如果添加相同的產品,也可以增加數量。 但是現在我需要添加相同的產品但大小不同,它應該創建另一個新數組。 下面是我使用的代碼..請幫忙..!!

switch (action.type) {
case ADD_TO_CART:
    const productId = action.product.id;

    if (findIndex(state.cart, product => product.id === productId) !== -1) {
        const cart = state.cart.reduce((cartAcc, product) => {
            if (product.id === productId) {
                // if (product.size === action.size) {
                    cartAcc.push({ ...product, size: parseInt(product.size), qty: parseInt(product.qty) + parseInt(action.qty), sum: (product.discount ? product.salePrice : product.price) * (parseInt(product.qty) + parseInt(action.qty)) }) // Increment qty
                // } else {
                //     cartAcc.push(product)
                // }

            } else {
                cartAcc.push(product)
            }
            return cartAcc
        }, [])

        return { ...state, cart }
    }
    return {
        ...state,
        cart: [
            ...state.cart,
            {
                ...action.product,
                qty: action.qty,
                size: action.size,
                sum: (action.product.discount ? action.product.salePrice : action.product.price) * action.qty
            }
        ]
    }

你快完成了,只需檢查大小相等(在 findIndex 和隨后的 if 中):

const productId = action.product.id;
const size = action.size;

if (findIndex(state.cart, product => (product.id === productId && product.size === size)) !== -1) {
        const cart = state.cart.reduce((cartAcc, product) => {
            if (product.id === productId  && product.size === size) {
                    cartAcc.push({ ...product, size: size, qty: parseInt(product.qty) + parseInt(action.qty), sum: (product.discount ? product.salePrice : product.price) * (parseInt(product.qty) + parseInt(action.qty)) }) // Increment qty
            } else {
                cartAcc.push(product)
            }
            return cartAcc
        }, [])

        return { ...state, cart }
    }

您的代碼是正確的,但是您需要為每個具有特定屬性的產品提供唯一的產品 ID。 例如

Product: { id: 'Nike' size: 's' color: 'blue'}

您的購物車有多個商品,其中此產品示例的 ID 為:“Nike,s,blue”。 每次您嘗試使用該特定 ID 查找此產品時,您都可以將其添加為新產品或增加它(如果它已經存在)。

您可以對 T 恤“L”采用相同的邏輯,其 ID 為:“Nike,L,blue”。 它使它成為一個新產品並分離。

簡而言之:您需要為每個產品及其屬性創建一個唯一的 ID(您可以根據您擁有數據的 Object.values 或數組將屬性與 ID 結合起來)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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