我正在尝试使用传播对象在列表中添加对象,但无法正确添加它。这是添加对象时initialState
的结果:
initialState = {
staters: [{name: 'chips', price: 7.5}],
mains: [{name: 'pizza', price: 9.9}],
deserts: [{name: 'ice cream', price: 8.2}],
drinks: [{name: 'whisky', price: 6}]
};
这应该是正确的结果:
const initialState = {
foods: {
staters: [{name: 'chips', price: 7.5}],
mains: [{name: 'pizza', price: 9.9}],
deserts: [{name: 'ice cream', price: 8.2}],
drinks: [{name: 'whisky', price: 6}]
},
isLoading: true
};
这是我使用的减速器:
const initialState = {
foods: {
staters: [],
mains: [],
deserts: [],
drinks: []
},
isLoading: true
};
const reducer = (state, action) => {
const { type, payload } = action;
const { type_plate } = payload.food;
const { foods } = state;
switch (type) {
case ADD_FOOD:
return {
...state,
foods: {
...foods,
[type_plate]: [...foods[type_plate], payload.food]
}
};
}
};
1)添加默认的初始状态2)添加菜名
假设payload = { food: { type_plate: 'starters', name_plate: 'baby corn' }}
const reducer = (state = { ...initialState }, action) => {
const { type, payload } = action;
const { type_plate, name_plate } = payload.food;
const { foods } = state;
switch (type) {
case ADD_FOOD:
return {
...state,
foods: {
...foods,
[type_plate]: [...foods[type_plate], name_plate]
}
};
}
};