使用嵌套地图ES6更新状态



我的状态具有一系列对象,其中还包含一个对象。

var state = {
  prop1: null,
  categories: [
    {
      categoryId: 1,
      tags: [
        {
          tagId: 1,
          name: 'AA11',
          status: true,
        },
        {
          tagId: 2,
          name: 'AA22',
          status: false,
        }
      ]
    },
    {
      categoryId: 2,
      tags: [
        {
          tagId: 1,
          name: 'BB11',
          status: true,
        },
        {
          tagId: 2,
          name: 'BB22', 
          status: false, // let's say i want to toggle this
        }
      ]
    },
  ]
};

我有一个动作可以切换标签状态。此操作将接收参数categoryIdtagId

到目前为止,我想出了这个,但它不起作用

return {
  ...state,
  categories: state.categories.map((category) => {
    category.tags.map(tag => (
      (tag.tagId === action.tagId && category.categoryId === action.categoryId) ? {
        ...tag,
        status: !tag.status,
      } : tag));
    return category;
  }),
};

我最终修复了地图代码。

return {
  ...state,
  categories: state.categories.map(category => ((category.id === action.categoryId) ?
    {
      ...category,
      tags: category.tags.map(tag => (tag.id === action.tagId ? {
        ...tag, status: !tag.status,
      } : tag)),
    } : category)),
};

最新更新