我在reducer函数中返回新状态时遇到问题。我的状态是一组对象。每个对象都有两个键值对类别:">和项:[{},{},{}]。
const initialState = [
{
category: 'vegetables',
items: [
{
id: 1,
name: 'carrot',
amount: 3,
unit: 'pc',
},
{
id: 2,
name: 'potato',
amount: 1,
unit: 'kg',
},
{
id: 3,
name: 'broccoli',
amount: 2,
unit: 'pc',
},
],
},
{
category: 'fruits',
items: [
{
id: 4,
name: 'orange',
amount: 4,
unit: 'pc',
},
{
id: 5,
name: 'blueberries',
amount: 250,
unit: 'g',
},
],
},
{
category: 'drinks',
items: [
{
id: 6,
name: 'Coca Cola',
amount: 2,
unit: 'l',
},
{
id: 7,
name: 'Grapefruit juice',
amount: 1,
unit: 'l',
},
{
id: 8,
name: 'Water',
amount: 1,
unit: 'l',
},
],
},
{
category: 'cereal products',
items: [
{
id: 9,
name: 'Cereal',
amount: 2,
unit: 'pack',
},
{
id: 10,
name: 'Muesli',
amount: 1,
unit: 'kg',
},
],
},
];
我想删除items数组中的项,并保持其余项不变。问题出在我的reducer函数中,我的switch语句返回了错误的值:
const rootReducer = (state = initialState, action) => {
switch (action.type) {
case 'REMOVE_ITEM':
state = [
state.map((element) => element.items.filter((item) => item.id !== action.payload.id)),
];
return state;
default:
return state;
}
};
我不是要求快速解决问题,但只要一个提示,我将不胜感激。
谢谢你们,伙计们!
我认为你的减速器应该是这样的:
const rootReducer = (state = initialState, action) => {
switch (action.type) {
case 'REMOVE_ITEM':
return state.map(element => ({
...element,
items: element.items.filter((item) => item.id !== action.payload.id))
})
default:
return state;
}
};
此解决方案假定;item.id";值在";initialState";范围
const rootReducer = (state = initialState, action) => {
switch (action.type) {
case 'REMOVE_ITEM':
state = state.map(element =>
Object.assign({}, element,
{items: element.items.filter(item => item.id !== action.payload.id)}
)
);
return state;
default:
return state;
}
};