如何在减速机中添加项目到arrayproperty?

时间:2016-12-05 23:29:49

标签: reactjs react-redux

尝试将我的itemsarray属性中的项目推送到redux reducer:

const initialState = {
    items: [],
    cartOpen: false,
    total: 0
}

const Cart = (state = initialState, action) => {
    switch (action.type) {
        case 'ADD_TO_CART':

            var newstate = Object.assign({}, state,
                {items: [state.items, ...action.payload.found]}
            );

            console.log('testing=newstate', newstate);

            var newTotal = 0;
            console.log('testing newstate', newstate)

            newstate.items.forEach(it => {
                newTotal += it.price;
                console.log('testing price', it.price)
            });
            newstate.total = newTotal;
            newstate.cartOpen = true
            //debugger;
            return newstate;


        default:
            return state
    }
}

export default Cart;

action.payload.found看起来像这样:

{
  "id":"100",
  "price":10
}

如何将此对象推送到items数组?

1 个答案:

答案 0 :(得分:0)

似乎你在错误的项目上使用传播操作符。你应该改用它:

        var newstate = Object.assign({}, state,
            {items: [...state.items, action.payload.found]}
        );

您的代码{items: [state.items, ...action.payload.found]}实际上试图传播action.payload.found这是一个对象,然后返回一个数组,其中第一个项目是旧数组,后跟action.payload.found

中的值

例如,假设原始state.items[A, B, C]action.payload.found{id: "100", price: 10},则{items: [state.items, ...action.payload.found]}实际上会返回[[A, B, C], "100", 10]。但是,您希望它返回[A, B, C, {id: "100", price: 10}]。因此,您需要传播state.items