2016-12-05 62 views
0

試圖在我的itemsarray物業推的項目爲我的終極版減速器:如何在減速器中將項目添加到arrayproperty?

const initialState = { 
    items: [], 
    cartOpen: false, 
    total: 0 
} 

const Cart = (state = initialState, action) => { 
    switch (action.type) { 
     case 'ADD_TO_CART': 

      var newstate = Object.assign({}, state, 
       {items: [state.items, ...action.payload.found]} 
      ); 

      console.log('testing=newstate', newstate); 

      var newTotal = 0; 
      console.log('testing newstate', newstate) 

      newstate.items.forEach(it => { 
       newTotal += it.price; 
       console.log('testing price', it.price) 
      }); 
      newstate.total = newTotal; 
      newstate.cartOpen = true 
      //debugger; 
      return newstate; 


     default: 
      return state 
    } 
} 

export default Cart; 

的action.payload.found看起來是這樣的:

{ 
    "id":"100", 
    "price":10 
} 

我怎麼可以把這個對象的物品數組?

回答

0

似乎你在錯誤的項目上使用傳播運算符。你應該使用這樣的:

 var newstate = Object.assign({}, state, 
      {items: [...state.items, action.payload.found]} 
     ); 

您的代碼{items: [state.items, ...action.payload.found]}真實目的是試圖傳播action.payload.found這是一個對象,然後返回一個數組,其中第一項是舊陣列隨後值從action.payload.found

例如假設原始state.items[A, B, C]action.payload.found{id: "100", price: 10},則{items: [state.items, ...action.payload.found]}實際上將返回[[A, B, C], "100", 10]。但是,您希望它返回[A, B, C, {id: "100", price: 10}]。因此您需要傳播state.items

+0

真棒老兄謝謝 –