簡體   English   中英

購物車/將多個項目添加到購物車

[英]Shopping cart / adding multiple items to cart

我正在嘗試使用 React js 和 Redux 創建一個購物車,但我遇到了一個問題。

嘗試了很多方法,但是當我將多個項目(食物/飲料)添加到列表中時,我總是失敗,然后一切似乎都在工作,但是當我想例如向現有選擇添加額外的飲料時,我的列表會被覆蓋。 這是我現在擁有的代碼:

const addItemToCart = item => {
   if (cartItems.length) {
     cartItems.forEach(itemToCheck => {
       if (item.name === itemToCheck.name) {
         addCountToItem({ ...itemToCheck, count: itemToCheck.count + 1 });
       } else if (item.name !== itemToCheck.name) {
         addToCart({ ...item, count: 1 });
       }
     });
   } else if (cartItems.length === 0) {
     addToCart({ ...item, count: 1 });
   }
 };

想法是我可以在列表中有多個項目,並且列表中可以有無限數量的相同項目。 所以基本上,我應該能夠有 5 個相同類型的比薩餅,3 個不同類型的啤酒等。

我想像任何其他購物車一樣。 提前致謝。

更新:

這里是 addCountToItem 的代碼。 我刪除了它,但它正朝着這個方向發展

state.cartItems[findIndex(...)] = data.cartItem

解決您的問題的基本方法是

`let index=cartItem.findIndex(temp=>temp.name===item.name);
 if(index>-1){
     cartItem[index].count++;
 }
 else{
     cartItem.append({...item, count: 1 })
 }`

盡量不要改變cartItem對象

我們還需要查看所有相關代碼才能成功回答。

這里我給出示例示例,updatedCartItems 保留更新后的購物車,您可以為所欲為。 一般來說,這種類型的操作必須在cart reducer 中,但您沒有發布reducer 代碼。

const addItemToCart = item => {
  let updatedCartItems = [...cartItems];

  updatedItemIndex = updatedCartItems.findIndex(
    item => item.name === itemToCheck.name   // better to check with some kind of id if exists
  );

  if (updatedItemIndex < 0) {
    updatedCartItems.push({ ...item, count: 1 });
  } else {
    const updatedItem = {
      ...updatedCartItems[updatedItemIndex]
    };
    updatedItem.count++;
    updatedCartItems[updatedItemIndex] = updatedItem;
  }

 //updatedCartItems  => the new cart
};

對於購物卡,我們需要在我們的狀態中將 carItems 屬性作為數組,每次我們點擊 addToCart 按鈕時,我們都會將該項目推送到該數組,然后我們在 cartDropdown 組件或結帳頁面中呈現該數組。

由於您可以將單個項目添加到購物車,這意味着您已正確設置了 redux。 為了多次將相同的項目添加到購物車,我們只需要編寫一個簡單的實用程序函數。

這是效用函數:

export const addItemToCart = (cartItems, cartItemToAdd) => {
  //find(condition) finds the first item in the array based on the condition.
  const existingCartItem = cartItems.find(item => item.id === cartItemToAdd.id);
  if (existingCartItem) {
    //in order for change detection to trigger we have to rerender
    //otherwise our quantity property will not be updated
    //map will return a new array 
    //we need to return new versions of our state so that our component know to re render
    //here we update the quantity property
    return cartItems.map(item =>
      item.id === cartItemToAdd.id
        ? { ...cartItemToAdd, quantity: item.quantity + 1 }
        : item
    );
  }
  //when you first time add a new item, sine exixtingCartItem will be falsy, it will pass the first if block and will come here
  //quantity property gets attached the first time around since this if block wont run when it is a new item.
 //in the beginning cartItems array is empty. every time you add a new item to this array, it will add "quantity:1" to this item object.  
  return [...cartItems, { ...cartItemToAdd, quantity: 1 }];
};

這是將商品添加到購物車的操作

export const CartActionTypes = {
  ADD_ITEM: "ADD_ITEM",
};

export const addItem = item => ({
  type: CartActionTypes.ADD_ITEM,
  payload: item
});

由於您可以將單個項目添加到購物車,這意味着您已正確設置了 redux。 您需要將其分派給呈現 addToCart 按鈕的組件中的減速器。 這是購物車減速器,案例是 CartActionTypes.ADD_ITEM。

import { addItemToCart } from "./cart.utils";

case CartActionTypes.ADD_ITEM:
      return {
        ...state,

        cartItems: addItemToCart(state.cartItems, action.payload)
      };

暫無
暫無

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

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