2016-12-16 80 views
1

的陣列如果非要說代表一個購物車對象的數組(以反應)減速作出反應函數返回的對象

[ { 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 
    } 
} 

回答

1

您可以使用Array.prototype.splice更換陣列用另一個文件:

case 'ADD_TO_CART': 
    const index = state.findIndex(item => item.id === action.payload.id) 
    if (index > -1) { 
    state.splice(index, 1, { 
     id: action.payload.id, 
     qty: state[index].qty + action.payload.qty 
    }) 
    return [...state] 
    } 
    else { 
    return [...state, { 
     id: action.payload.id, 
     qty: newQty 
    }] 
    } 
+0

的範例是用於陣列爲不可變的 – avrono

+0

我想我可以切片()第一 – avrono

+0

它是不可變的存在。 '[... state]'是一個新陣列。 – dfsq