redux更新一个嵌套对象的对象列表



我试图在我的redux存储中创建这个结构,有一个添加用户的功能,努力更新结构以向用户添加汽车,im传递对象认为我需要做一个地图状态但它无法正常工作的

// 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;

}
}

我认为您应该指定要向哪个用户添加car。您的ADD_CAR有效负载可以像这样:

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

在reducer中,您将首先通过userId找到用户,然后将car添加到该用户,如下所示:

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

相关内容

  • 没有找到相关文章

最新更新