下面的Reducer应该在我发送{"id": 14, 'quantity':3}
或{"id": 14, 'quantity':2}
时更新状态下特定对象的数量。
const initialState={ items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':1},{"id": 25,'quantity':1}] }
const cart =(state=initialState,action)=>{
switch(action.type){
case 'UPDATECART':{
//need updating code here
}
default: return state
}
}
export default cart
如何更新状态数组中的特定对象,而保持其他值不变?
现有对象的更新功能quantity
递增1
和id
将是永久性的。
拟议的工作流程
CURRENT STATE : items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':1},{"id": 25,'quantity':1}]
INCOMING OBJECT : {"id": 15,'quantity':2}
EXPECTED RESULTANT STATE : items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':3},{"id": 25,'quantity':1}]
答案 0 :(得分:1)
尝试:
case UPDATE CART:
const items = state.items;
const {id, quantity} = INCOMINGOBJECTORPAYLOAD; // destructure new object in 1 line
const oldQuantity = items.filter(item => item.id === id)[0].quantity
return {
[...items, {"id": 15,'quantity':oldQuantity+quantity}]
};
请注意,...items
是用于在数组中填充旧项(不需要任何更改)的“ spread”运算符
答案 1 :(得分:1)
您应该替换数组中的项目并返回新的状态引用,请尝试以下代码
const initialState = {
items: [
{ id: 14, quantity: 1 },
{ id: 15, quantity: 1 },
{ id: 25, quantity: 1 }
]
};
const cart = (state = initialState, action) => {
switch (action.type) {
case "UPDATECART": {
const index = state.items.findIndex(
item => item.id === action.payload.id
);
if (index >= 0) {
state.items[index] = {
id: action.payload.id,
quantity: action.payload.quantity
};
} else {
// add to array if not exist
state.items.push({
id: action.payload.id,
quantity: action.payload.quantity
});
}
return {
items: [...state.items] // creating new array
};
}
default:
return state;
}
};
export default cart;
答案 2 :(得分:1)
尝试一下:
case 'UPDATECART':{
//need updating code here
return state.map( cart => cart.id === INCOMING_OBJECT.id ? {...cart, quantity:
cart.quantity + INCOMING_OBJECT.quantity}: cart )
}