如果我有一个代表购物车的对象数组(在React中)
[ { id: 1, qty: 1 } ]
将一个项目添加到此state
会是一种巧妙的方式吗?
我需要检查数组是否包含具有该id的对象,如果有,则更新它的数量,否则只需创建一个添加此新对象的新数组元素。
我试图用功能风格的新ES6语法编写这个问题......这就是我到目前为止所做的......
let initialState = []
export default function shoppingCart(state=initialState, action) {
switch(action.type) {
case 'ADD_TO_CART':
// check the array of objects and only act on the one we are interested in
let newQty = action.payload.qty
console.log("state : ", state)
for(let i = 0; i < state.length; i++) {
if (state[i].id === action.payload.id) {
newQty = state[i].qty + action.payload.qty
console.log("QTY : " + newQty)
}
}
//Obviously this will not work if the {id ...} already exists
return [ ... state, {id:action.payload.id, qty:newQty} ] // todo: update this to contain the payload with qty included
case 'REMOVE_FROM_CART':
return state.filter(elem => elem.id !== action.payload.id)
default:
return state
}
}