You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Redux中用ES6条件式更新数组对象(Immutable更新)

Redux购物车更新问题

我在Redux项目中需要实现以下逻辑:

  • 当action.payload对象的id与state数组中对象的id匹配时,更新该对象的属性
  • 若id不匹配,则将该对象添加到state数组中
  • 必须以**Immutable(不可变)**的方式更新状态

但目前点击已加入购物车的商品时,无法更新其quantity和cartQuantity属性。以下是相关代码、当前状态结果及组件调用逻辑:

购物车Reducer代码

import initialState from "./initialState";

import { ADD_TO_CART, DELETE_FROM_CART } from "./actionType";

const cartReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_TO_CART:
      const itemToAdd = action.payload;
      const existingItemIndex = state.findIndex(
        (item) => item.id === itemToAdd.id
      );
      if (existingItemIndex !== -1) {
        // 如果商品已在购物车中,更新其quantity和cartQuantity
        return state.map((item) => {
          if (item.id === existingItemIndex) {
            return {
              ...item,
              quantity: itemToAdd.quantity - 1,
              cartQuantity: itemToAdd.cartQuantity + 1,
            };
          }
          return item;
        });
      } else {
        // 如果商品不在购物车中,添加并更新属性
        return [
          ...state,
          {
            ...itemToAdd,
            quantity: itemToAdd.quantity - 1,
            cartQuantity: itemToAdd.cartQuantity + 1,
          },
        ];
      }
    case DELETE_FROM_CART:
    default:
      return state;
  }
};

export default cartReducer;

当前购物车状态结果

cart = [
  {
    id: 2,
    name: "mackbook pro",
    category: "laptop",
    price: 16000,
    quantity: 9,
    imageUrl: "https://i.dummyjson.com/data/products/7/thumbnail.jpg",
    cartQuantity: 1,
  },
  {
    id: 1,
    name: "iphone13 pro max",
    category: "mobile phone",
    price: 12000,
    quantity: 19,
    imageUrl: "https://i.dummyjson.com/data/products/1/thumbnail.jpg",
    cartQuantity: 1,
  },
  {
    id: 3,
    name: "Iphone 14 ",
    category: "mobile phone",
    price: 35666,
    quantity: 9,
    imageUrl: "https://i.dummyjson.com/data/products/3/thumbnail.jpg",
    cartQuantity: 1,
  },
];

商品组件调用逻辑

import { useDispatch } from "react-redux";
import { addToCart } from "../redux/cart/actions";
export default function ProductItem({ product }) {
  const { id, name, category, price, quantity, imageUrl, cartQuantity } = product;

  const dispatch = useDispatch();

  const handleAddToCart = () => {
    dispatch(
      addToCart({
        id,
        name,
        category,
        price,
        quantity,
        imageUrl,
        cartQuantity,
      })
    );
  };

  return (
    <div className='lws-productCard'>
      <img className='lws-productImage' src={imageUrl} alt='product' />
      <div className='p-4 space-y-2'>
        <h4 className='lws-productName'>{name}</h4>
        <p className='lws-productCategory'>{category}</p>
        <div className='flex items-center justify-between pb-2'>
          <p className='productPrice'>
            BDT <span className='lws-price'>{price}</span>
          </p>
          <p className='productQuantity'>
            QTY <span className='lws-quantity'>{quantity}</span>
          </p>
        </div>
        <button
          className='lws-btnAddToCart'
          onClick={() => handleAddToCart()}
          disabled={!quantity}
        >
          Add To Cart
        </button>
      </div>
    </div>
  );
}

内容的提问来源于stack exchange,提问作者Joyram Das

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 22:34:54