我正在尝试在我的 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;
}
}
我认为您应该指定要将汽车添加到哪个用户。您的 ADD_CAR 有效负载可能如下所示:
{ userId, carOptions: { model: "Porsche", year: "2009" } }
在reducer中,你将首先通过userId找到用户,然后将汽车添加到该用户,像这样:
return state.map((user) =>
user.id === action.payload.userId
? { ...user, cars: [...user.cars, action.payload.carOptions] }
: user
);