我目前正在開發一個多供應商專案。我正在嘗試添加一個功能,如果客戶想從不同的供應商商店購買產品,它不會添加到購物車中。他必須從同一個供應商那里購物。
假設有兩個供應商 x 和 y。客戶想從兩個供應商商店購買,但功能不會嘗試這樣做,他必須從 x 商店或 y 商店購買。
我的添加到購物車功能已準備就緒,但我對如何應用 if 條件感到困惑。
我正在使用 redux 進行狀態管理。這是我的購物車減速器
addToCart: (state: any, { payload }: { payload: any }) => {
const itemIndex = state.cart.findIndex(item => item._id === payload._id)
// here I am checking is the vendor already available into the cart or not
const isAlreadyVendor = payload?.vendor?.email ?? state.cart.findIndex(item => item.vendor.email === payload.vendor?.email)
// Need to make an if condition here but confused how it would be.
if (itemIndex >= 0) { // this will increase the quantity
state.cart[itemIndex].cartQuantity = 1
toast.info(`${payload.title} quantity increased`, {
position: 'bottom-left'
})
} else {
const newCart = { ...payload }
state.cart.push(newCart)
toast.success(`${payload.title} added to cart`, {
position: 'bottom-left'
})
}
localStorage.setItem("cartItems", JSON.stringify(state.cart));
}
在上面的代碼中,有一個變數isAlreadyVendor將回傳 -1 或 1。所以基本上我試圖在isAlreadyVendor-1 時執行,然后用戶可以添加任何產品,但在第二次單擊立即購買按鈕后,功能將檢查isAlreadyVendor是回傳 -1 或 1 如果 1 表示用戶正在嘗試從同一供應商處購買,那么第二個產品也將添加到購物車中,但如果isAlreadyVendor回傳 -1 則不會添加任何內容(我們可以顯示警報)
uj5u.com熱心網友回復:
// Every item in the cart needs to have the same vendor
// Also okay if the cart is empty.
const isSameVendor = state.cart.every(c => c.vendor.email === payload.vendor.email;
if (!isSameVendor) {
alert();
// Or maybe
clearCart();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/443109.html
標籤:javascript 数组 反应 目的 还原
