【问题标题】:Shopping cart / adding multiple items to cart购物车/将多个商品添加到购物车
【发布时间】:2020-01-14 07:57:45
【问题描述】:

我正在尝试使用 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

【问题讨论】:

  • 你能分享 addToCart、addCountToItem 的代码和你的购物车减速器代码吗?
  • 刚刚添加了我删除之前的内容..现在无法完全回忆起该功能:/
  • 这不是您使用 redux 将商品添加到购物车的方式。你必须创建你的动作和减速器,然后将动作分派给减速器

标签: javascript reactjs react-redux shopping-cart


【解决方案1】:

解决问题的基本方法是

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

尽量不要改变 cartItem 对象

【讨论】:

    【解决方案2】:

    我们也需要查看所有相关代码才能成功回答。

    这里我举个例子,updatedCartItems 保存更新的购物车,你可以做任何你想做的事。一般来说,这种类型的操作必须在购物车减速器中,但您没有发布减速器代码。

    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
    };
    

    【讨论】:

      【解决方案3】:

      对于购物卡,我们需要在状态中将 cartItems 属性作为数组,每次单击 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)
            };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-19
        • 1970-01-01
        • 1970-01-01
        • 2015-03-31
        相关资源
        最近更新 更多