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

如何使用扩展运算符替换数组值,正确更新嵌套状态的购物车商品数量

问题原因

你构造新状态的层级逻辑错误:把...state.cart直接展开到了state根节点,同时将products也声明在根节点,所以才会出现根节点新增独立products数组、cart内部products没有被修改的问题。

修正方案

1. 修正reducer中的状态构造逻辑

修改状态合并层级,把products的更新放到cart属性内部:

on(increaseItemQuantity, (state, action) => {
    const newItems = increaseQuantity(state, action.itemId, action.size);

    const newState  = {
        ...state,
        cart: {
            ...state.cart,
            products: newItems
        },
        // 若需要同步更新商品总数,可添加下方逻辑
        // numberOfItems: newItems.reduce((total, item) => total + item.quantity, 0)
    }

    return newState;
}),

2. 修正increaseQuantity中的筛选逻辑

你当前的filter逻辑使用了&&,会误删和目标商品同id不同尺寸、或同尺寸不同id的商品,需要改为||:

const increaseQuantity = (state, itemId, size) => {
    console.log('state.cart.products', state.cart.products)
    const item = state.cart.products.find(item => item._id === itemId && 
        item.size === size);

    const newItem = {...item};

    ++newItem.quantity;

    // 把 && 改为 ||
    let  newItems = state.cart.products.filter(item => item._id !== itemId || item.size !== size);

    newItems.push(newItem);

    return newItems;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 05:36:03