如何在Redux上动态更新对象数组的键?

我从数据库获得此数组:

pages: [
      {
        key: 0,
        menuName: 'Home',
        pageType: 'HomePage',
        dataIndex: 'HomePage0'
      },
      {
        key: 1,
        menuName: 'Employer Chat',
        pageType: 'EmployerChat',
        dataIndex: 'EmployerChat1'
      },
      {
        key: 2,
        menuName: 'IT Jobs',
        pageType: 'JobOpenings',
        dataIndex: 'JobOpenings2'
      }      
]

减速器(稍后我将解释LOAD_COPIES操作):

export const initialState = { pages: [] };

export const dynamicMenuReducer = (state = initialState, action) => {
  switch (action.type) {
    case LOAD_PAGES:
      return {
        ...state,
        pages: [...state.pages, action.pages],
      };
    case LOAD_COPIES:
      return {
        ...state,
        copies: action.copies,
      };
  };

}

行动:

export const loadPagesAction = (pages) => ({ pages, type: LOAD_PAGES });

export const loadCopiesAction = (copies) => ({ copies, type: LOAD_COPIES });

这就是我在react组件中执行的操作以加载页面和副本:

useEffect(() => {
    if (siteById.data && loadPagesAction) {
      siteById.data.pages.map((p, index) => {
        const page = {
          key: index,
          menuName: p.menuName,
          pageType: p.pageType,
          dataIndex: p.pageType + index,
        };

        loadPagesAction(page);
      });
    }
}, [siteById, loadPagesAction]);

useEffect(() => {
    if (pages.length) {
      loadCopiesAction(pages);
    }
}, [pages]);

我必须将此数组呈现为菜单,并为用户提供编辑项目名称的选项。因此,我想到了创建这些项目的副本并更改状态的想法,如下所示:

const handleInputsChange = (e) => {
    loadCopiesAction(
      copies.map((p) => {
        if (p.dataIndex === e.target.name) {
          return {
            ...p,
            menuName: e.target.value,
          };
        }

        return { ...p };
      })
    );
};

没关系,它可以在某些时候起作用,但是它带来了很多其他问题,因为我需要菜单具有10种不同的功能,并且原始数组和副本在每次迭代中都不同。

So how can I update the menuName key directly from Redux without having to mutate the state and creating a copy and all of that?

评论