【问题标题】:Not displaying quantity of object in my product cart on UI不在 UI 上显示我的产品购物车中的对象数量
【发布时间】:2022-12-14 03:27:32
【问题描述】:
I am using API of a fake store, so when I add a product to my cart I need to update the quantity of this product in the cart and update the quantity on UI. The problem is that product quantity is updating in global state, but not updating on UI. Could you please give any advice on that? Thank you in advance !


const reducer = (state= initialState, action) => { 开关(动作类型){ 案例“ADD_TO_CART”: const newItem = action.payload const exist = state.products.find((item) => item.id === newItem.id); 如果(存在){ 存在.数量+=1 返回 { ...状态, 数量:state.quantity + 1 } } 别的 { 新物品.数量 = 1 返回{ ...状态, 产品:state.products.concat(newItem) } }

【问题讨论】:

  • 请分享价值initialState
  • const initialState ={ 产品: [], }

标签: react-redux


【解决方案1】:

reducer 函数应该始终返回新状态,而不是改变现有状态。当你执行 exist.qty += 1 时,你正在改变状态。此外,在 if 块中,当您执行 quantity: state.quantity + 1, 时,您将在您的状态中添加一个新属性。

假设每个产品至少具有这些属性:id 和`数量,这应该有效:

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case "ADD_TO_CART":
      const newItem = action.payload;

      // Clone existing products array
      let updatedProducts = [...state.products];

      // Find the index of the product you want to add
      const existingIndex = updatedProducts.find((item) => item.id === newItem.id);

      // If the product exists (it will have an index of > -1)
      if (existingIndex > -1) {
        // Increase its quantity
        const updatedProduct = { ...updatedProducts[index], quantity: ++updatedProducts[index].quantity };

        // Update the item in the array
        updatedProduct.splice(existingIndex, 1, updatedProduct);
      } else {
        // Product was not found in products - so add it at the end, with quantity set to 1
        updatedProducts = [...updatedProducts, { ...action.payload, quantity: 1 }];
      }

      // Return the state
      return { products: updatedProducts };
  }
};

【讨论】:

    猜你喜欢
    • 2021-11-08
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    相关资源
    最近更新 更多