【发布时间】:2021-01-27 21:53:33
【问题描述】:
我在 reducer 函数中返回新状态时遇到问题。我的状态是一组对象。每个对象都有两个键值对category: '' 和items: [{}, {}, {}]。
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;
}
};
我不是要求快速修复,但如果只是一个提示,将不胜感激。
谢谢你们!
【问题讨论】:
-
您不会在操作中返回任何内容。
-
你的新状态被一个额外的数组包裹着。例如
[[ { ... } ]]
标签: reactjs react-redux switch-statement reducers redux-reducers