繁体   English   中英

当我的状态是数组而不是对象时,如何使用 reducer 更新状态

[英]how to update state with reducer, when my state is an array not an object

我在 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;
  }
};

我不是要求快速修复,但只是一个提示将不胜感激。

谢谢你们!

此解决方案假定“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;
  }
};

我认为你的减速器应该是这样的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM