【问题标题】:remove full object from Redux initial state when there is no values in the corresponding items当相应项中没有值时,从 Redux 初始状态中删除完整对象
【发布时间】:2020-10-24 04:24:59
【问题描述】:

在我的减速器中,我的初始状态如下所示:

    const initialState = {
        isLoading: false,
        events: [
        {
        year: 2021,
        place: [
        {
          id: 1,
          name: "BD"
        },
        {
          id: 2,
          name: "BD Test"
        }
      ]
    },
    { year: 2020, place: [{ id: 3, name: "AMS" }, { id: 4, name: "AMS TEST" }] }
  ]
};

我一直在尝试实现删除操作的功能。因此,当单击按钮时,将调度“deleteItems”操作,该操作将从place 中删除相应的项目。此功能工作正常。但是,如果place 中没有值,我会尝试从events 数组中删除整个项目。

这是我已经尝试过的,但它只是删除了个人place。但是,我需要在这里编写当place 变为空时删除整个项目的逻辑。

case "deleteItems":
  return {
    ...state,
    events: state.events.map(event => {
      const place = event.place.find(x => x.id === action.id);
      if (place) {
        return {
          ...event,
          place: event.place.filter(x => x.id !== action.id)
        };
      }
      return event;
    })
  };

因此,在修改后,状态将如下所示:(当没有 2021 年的值时)

const initialState = {
  isLoading: false,
  events: [
    { year: 2020, place: [{ id: 3, name: "AMS" }, { id: 4, name: "AMS TEST" }] }
  ]
};

有谁知道如何做到这一点。任何帮助将不胜感激。在此先感谢。 Demo可以看here

【问题讨论】:

    标签: javascript arrays reactjs redux react-redux


    【解决方案1】:

    我先删除了这些地方。 然后我根据位置数组是否为空来过滤事件。 之后,我返回了状态。

    case "deleteItems":
          const eventsPostDeletingPlaces = state.events.map(event => {
            const place = event.place.find(x => x.id === action.id);
            if (place) {
              return {
                ...event,
                place: event.place.filter(x => x.id !== action.id)
              };
            }
            return event;
          });
          const eventsWithPlaces = eventsPostDeletingPlaces.filter((each) => each.place.length);
          return {
            ...state,
            events: eventsWithPlaces
          }
    

    查看编辑后的沙箱here

    【讨论】:

    • 感谢您的回答。我已经接受了。我还试图在您的答案之上编写一个逻辑,如果年份是当前和明年,我不需要删除整个事件数组。有没有可能帮我解决这个问题。
    • 如果我错了,请纠正我,但这就是我对这里要求的理解。如果内部没有位置(现有功能),您想要删除事件,但前提是年份不是当前或明年。如果这是必需的,请检查此代码框link 以获取更新的代码。
    • 是的,这就是我尝试过的,我的错误是我无法做出这样的逻辑(似乎直截了当)。再次感谢
    【解决方案2】:

    与第一个答案中的逻辑基本相同,但使用reduce 而不是map 和额外的filter。只是一种选择。

    case "deleteItems":
      return {
        ...state,
        events: state.events.reduce((events, event) => {
          const place = event.place.find(x => x.id === action.id);
    
          if (place) {
            event.place = event.place.filter(x => x.id !== action.id);
          }
    
          if (event.place.length > 0) {
            events.push(event);
          }
    
          return events;
        }, [])
      };
    

    codesandbox

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-29
      • 2016-10-13
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多