从reducer中的数组中删除Item无效

时间:2018-01-23 15:50:46

标签: reactjs redux react-redux

我正在尝试从减速机中的购物车中删除单个商品但不是它似乎不起作用。 itemsInCart在ADD_TO_CART中更新,但在REMOVE_FROM_CART中未更新。

任何人都可以建议编辑我的代码....

我尝试将可变/不可变参数传递给manageItemCount()

function manageItemCount(allItems, newItem){
    let itemIndex = [];
    if(allItems.length > 0) {
        allItems.forEach((elem, i) => { 
            if (elem.product.id == newItem.product.id) {
                itemIndex.push(i);
            }; 
        });

        if(itemIndex.length){
            allItems.splice(itemIndex.length-1, 1);
        }
    }
    return allItems;
}

let alreadyRemovedFromCart = false;

const cartReducer = (state = {
    itemsInCart: []
}, action) => {
    switch (action.type) {
        case 'ADD_TO_CART':
            state = {
                ...state,
                itemsInCart: [...state.itemsInCart, action.payload]
            };
            break;
        case 'REMOVE_FROM_CART':
            state = {
                ...state,
                itemsInCart: manageItemCount(...state.itemsInCart, action.payload)
            };
            break;
    }

    return state;
}

export default cartReducer;

1 个答案:

答案 0 :(得分:1)

manageItemCount接受两个参数,但您正在传播所有itemsInCart数组。所以它应该是:

case 'REMOVE_FROM_CART':
  state = {
    ...state,
    itemsInCart: manageItemCount(state.itemsInCart, action.payload)
  };
  break

同样manageItemCount似乎只在.filter上进行了itemsInCart