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

问题描述

我在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,],{
    category: 'fruits',items: [
      {
        id: 4,name: 'orange',amount: 4,{
        id: 5,name: 'blueberries',amount: 250,unit: 'g',{
    category: 'drinks',items: [
      {
        id: 6,name: 'Coca Cola',unit: 'l',{
        id: 7,name: 'Grapefruit juice',{
        id: 8,name: 'Water',{
    category: 'cereal products',items: [
      {
        id: 9,name: 'Cereal',unit: 'pack',{
        id: 10,name: 'Muesli',];

我想删除项目数组中的项目,其余部分保持不变。问题出在我的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;
  }
};

我不要求快速解决问题,但只要提示即可。

谢谢你们!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)