Reactjs React Reducer函数返回对象数组

Reactjs React Reducer函数返回对象数组,reactjs,reducers,ecmascript-2016,Reactjs,Reducers,Ecmascript 2016,如果我有一个表示购物车的对象数组(在React中) 向该状态添加项目的简洁方法是什么 我需要检查数组是否包含具有该id的对象,如果包含,则更新其数量,如果不包含,则仅创建一个新的数组元素添加此新对象 我正试图用新的ES6语法以函数式的方式写这篇文章,这让我陷入了困境。。。这就是我目前所拥有的 let initialState = [] export default function shoppingCart(state=initialState, action) { switch(

如果我有一个表示购物车的对象数组(在React中)

向该
状态添加项目的简洁方法是什么

我需要检查数组是否包含具有该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
   }
}
let initialState=[]
导出默认功能shoppingCart(状态=初始状态,操作){
开关(动作类型){
案例“添加到购物车”:
//检查对象数组,只对我们感兴趣的对象执行操作
让newQty=action.payload.qty
日志(“状态:”,状态)
for(设i=0;ielem.id!==action.payload.id)
违约:
返回状态
}
}
您可以使用以另一个数组项替换数组项:

案例“添加到购物车”:
const index=state.findIndex(item=>item.id==action.payload.id)
如果(索引>-1){
状态。拼接(索引,1{
id:action.payload.id,
数量:状态[索引]。数量+动作。有效负载。数量
})
返回[…状态]
}
否则{
返回[…状态{
id:action.payload.id,
数量:新数量
}]
}

这个范例是数组不可变的,我想我可以先切片()它在那里是不可变的<代码>[…状态]
是一个新数组。就是这样。有道理。Tks!
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
   }
}