亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

白豬掌柜的 2023-03-24 14:36:08
我可以將不同的產品添加為單獨的數組,如果添加相同的產品,也可以增加數量。但現在我需要添加相同的產品但尺寸不同,它應該創建另一個新數組。下面是我正在使用的代碼..請幫忙..!!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            }        ]    }
查看完整描述

2 回答

?
收到一只叮咚

TA貢獻1821條經驗 獲得超5個贊

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

Product: { id: 'Nike' size: ['S', 'M', 'L'] color: ['blue', 'white', 'black']}

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

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

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


查看完整回答
反對 回復 2023-03-24
?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

你幾乎完成了,只需檢查大小是否相等(在 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 }

    }


查看完整回答
反對 回復 2023-03-24
  • 2 回答
  • 0 關注
  • 143 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號