【发布时间】:2016-12-16 14:58:29
【问题描述】:
如果我有一个代表购物车的对象数组(在 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
}
}
【问题讨论】:
标签: reactjs reducers ecmascript-2016