如何将项目添加到 reducer 中的 arrayproperty?
How to add item to arrayproperty in reducer?
正在尝试为我的 redux reducer 在我的 itemsarray 属性 中推送一个项目:
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
}
如何将此对象推送到项目数组?
您似乎在错误的项目上使用了展开运算符。你应该改用这个:
var newstate = Object.assign({}, state,
{items: [...state.items, action.payload.found]}
);
你的代码 {items: [state.items, ...action.payload.found]}
实际上试图传播 action.payload.found
这是一个对象,然后 returned 一个数组,其中第一项是旧数组,后面是 action.payload.found
例如假设原来的 state.items
是 [A, B, C]
而 action.payload.found
是 {id: "100", price: 10}
,那么 {items: [state.items, ...action.payload.found]}
实际上是 return [[A, B, C], "100", 10]
.但是,您希望它改为 return [A, B, C, {id: "100", price: 10}]
。因此你需要传播 state.items
.
正在尝试为我的 redux reducer 在我的 itemsarray 属性 中推送一个项目:
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
}
如何将此对象推送到项目数组?
您似乎在错误的项目上使用了展开运算符。你应该改用这个:
var newstate = Object.assign({}, state,
{items: [...state.items, action.payload.found]}
);
你的代码 {items: [state.items, ...action.payload.found]}
实际上试图传播 action.payload.found
这是一个对象,然后 returned 一个数组,其中第一项是旧数组,后面是 action.payload.found
例如假设原来的 state.items
是 [A, B, C]
而 action.payload.found
是 {id: "100", price: 10}
,那么 {items: [state.items, ...action.payload.found]}
实际上是 return [[A, B, C], "100", 10]
.但是,您希望它改为 return [A, B, C, {id: "100", price: 10}]
。因此你需要传播 state.items
.