2016-12-05 58 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

真棒老兄谢谢 –