简体   繁体   English

React redux 更新对象列表嵌套对象

[英]React redux update a list of objects nested objects

Im trying to create this structure in my redux store, havea feature to add a user,struggling to update the structure to add cars to a user , im passing object think i need to do a map on state but its not working correctly我试图在我的 redux 商店中创建这个结构,具有添加用户的功能,努力更新结构以向用户添加汽车,我传递对象认为我需要在状态上做一个映射,但它不能正常工作

 // main object im trying to build const inventory = [ { id: 1, name: "Paul", cars: [ { model: "Ford", year: "1995", }, { model: "BMW", year: "2010", }, ], }, { id: 2, name: "Simon", cars: [ { model: "Vauxhall", year: "2022", }, { model: "VW", year: "2001", }, ], }, ]; // object that gets sent to the store const addUser = (content) => ( { type: 'ADD_USER', payload: { id : 1, name : 'George', cars : [] } } ) const carOptions = (content) => ( { type : "ADD_CAR", payload : { model: "Porsche", year: "2009" } } ) This is my reducer main issue appears in ADD_CAR const carReducer = ( state = [], action) => { switch(action.type) { case 'ADD_USER': return [...state,action.payload] case 'ADD_CAR': return state.map((item) => item.id === 1 ? { ...item, cars: item.cars.concat([ ...state, action.payload ]) } : item ); default: return state; } }

I think you should specify to which user you want to add car to.我认为您应该指定要将汽车添加到哪个用户。 Your ADD_CAR payload can look like this:您的 ADD_CAR 有效负载可能如下所示:

{ userId, carOptions: { model: "Porsche", year: "2009" } }

In reducer you will first find the user by userId and then add car to this user, smth like this:在 reducer 中,您将首先通过 userId 找到用户,然后将汽车添加到该用户,就像这样:

return state.map((user) =>
    user.id === action.payload.userId
      ? { ...user, cars: [...user.cars, action.payload.carOptions] }
      : user
  );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM