代码之家  ›  专栏  ›  技术社区  ›  publicArt33

更新redux数组中的多个项

  •  1
  • publicArt33  · 技术社区  · 6 年前

    我正在尝试更新redux状态下的对象数组,

    cars:  [
      {
        _id:"5b61b782719613486cdda7ec",
        car: "BMW",
        year: '2015'
       },
       {
          _id:"5b61b782719613486cdda7e1",
          car: "Toyota",
          year: '2015'
        },
        {
          _id:"5b61b782719613486cdda7e2",
          car: "Honda",
          year: '2015'
        },
        {
          _id:"5b61b782719613486cdda7e3",
          car: "Audi",
          year: '2015'
        }
     ]
    

    action.payload数组

     action.payload :      
       [
        {
          _id:"5b61b782719613486cdda7ec",
          car: "BMW",
          year: '2019'
        },
        {
          _id:"5b61b782719613486cdda7e3",
          car: "Audi",
          year: '2019'
        }
      ]
    
    
    case UPDATE_CARS:
      const updatedCars = state.cars.map((car) => {
      action.payload.forEach((newCars, index) => {
        if (car._id !== newCars._id) {
          //This is not the item we care about, keep it as is
          return car;
        } else {
          //Otherwise, this is the one we want to return an updated value
          return { ...car, ...newCars };
        }
      });
    });
    
    return {
      ...state,
      cars: updatedCars,
      loading: false
    };
    

    我做错什么了?有什么建议吗?

    2 回复  |  直到 6 年前
        1
  •  6
  •   devserkan    6 年前

    另一种选择:

    const updatedCars = state.cars.map( car => {
      const found = action.payload.find( el => el._id === car._id );
      return found ? found : car;
    });
    

    forEach return anything ,它只执行当前元素的给定函数。所以,在这种情况下 map 是你的朋友。

    甚至还有一个更短更好的版本,@Luke M Willis在评论中提供:

    const updatedCars =
        state.cars.map(car => action.payload.find(el => el._id === car._id) || car);
    
        2
  •  1
  •   Arup Rakshit    6 年前

    我把车过滤掉 state action.payload . 然后我将合并 ,并筛选 状态

    case UPDATE_CARS:
      const updatedCarIds = action.payload.map(o => o.id);
      const notUpdatedCars = state.cars.filters(car => !updatedCarIds.includes(car.id))
      return [...notUpdatedCars, ...action.payload]