【问题标题】:how to update state with reducer, when my state is an array not an object当我的状态是数组而不是对象时,如何使用减速器更新状态
【发布时间】: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


【解决方案1】:

我认为你的 reducer 应该是这样的:

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

【讨论】:

  • 是的!太感谢了!它现在正在工作!我肯定需要刷一下我的 ES6 xD
  • 太好了,请不要忘记接受对您帮助最大的答案。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2016-10-06
    • 2021-12-26
    • 2021-07-18
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    相关资源
    最近更新 更多