React Redux,状态中特定项目的更新

时间:2020-05-28 14:05:17

标签: reactjs redux react-redux

下面的Reducer应该在我发送{"id": 14, 'quantity':3}{"id": 14, 'quantity':2}时更新状态下特定对象的数量。


const initialState={ items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':1},{"id": 25,'quantity':1}] }

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

             //need updating code here

                 }       
        default: return state
    }
}

export default cart

如何更新状态数组中的特定对象,而保持其他值不变?

现有对象的更新功能quantity递增1id将是永久性的。

拟议的工作流程

 CURRENT STATE : items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':1},{"id": 25,'quantity':1}] 
    INCOMING OBJECT : {"id": 15,'quantity':2}
    EXPECTED RESULTANT STATE : items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':3},{"id": 25,'quantity':1}] 

3 个答案:

答案 0 :(得分:1)

尝试:

    case UPDATE CART:
      const items = state.items;
      const {id, quantity} = INCOMINGOBJECTORPAYLOAD; // destructure new object in 1 line
      const oldQuantity = items.filter(item => item.id === id)[0].quantity

      return {
        [...items, {"id": 15,'quantity':oldQuantity+quantity}]
      };

请注意,...items是用于在数组中填充旧项(不需要任何更改)的“ spread”运算符

答案 1 :(得分:1)

您应该替换数组中的项目并返回新的状态引用,请尝试以下代码

const initialState = {
  items: [
    { id: 14, quantity: 1 },
    { id: 15, quantity: 1 },
    { id: 25, quantity: 1 }
  ]
};

const cart = (state = initialState, action) => {
  switch (action.type) {
    case "UPDATECART": {
      const index = state.items.findIndex(
        item => item.id === action.payload.id
      );
      if (index >= 0) {
        state.items[index] = {
          id: action.payload.id,
          quantity: action.payload.quantity
        };
      } else {
        // add to array if not exist
        state.items.push({
          id: action.payload.id,
          quantity: action.payload.quantity
        });
      }
      return {
        items: [...state.items] // creating new array
      };
    }
    default:
      return state;
  }
};

export default cart;

答案 2 :(得分:1)

尝试一下:

case 'UPDATECART':{

         //need updating code here
     return state.map( cart => cart.id === INCOMING_OBJECT.id ? {...cart, quantity: 
     cart.quantity + INCOMING_OBJECT.quantity}: cart )

             }