尝试将我的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数组?
答案 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
。