为什么非正规化不返回嵌套对象?

时间:2019-05-24 12:41:42

标签: javascript redux normalization normalizr

我使用denormalize包中的normalizr作为以下代码:

import { normalize, schema, denormalize } from 'normalizr';

const categoriesData = [
  { id: 1, name: 'category-1' },
  { id: 2, name: 'category-2' },
  { id: 3, name: 'category-3' },
  { id: 40, name: 'category-40' },
];

const subCategoriesData = [
  { id: 1, name: 'sub-category-a', category: 1 },
  { id: 2, name: 'sub-category-b', category: 2 },
  { id: 3, name: 'sub-category-c', category: 1 },
  { id: 4, name: 'sub-category-d', category: 3 },
  { id: 500, name: 'sub-category-e', category: 40 },
]

const category = new schema.Entity('categories');
const categories = new schema.Array(category);

const subcategory = new schema.Entity('subCategories');
const subcategories = new schema.Array(subcategory);

const normalizedData = normalize(categoriesData, categories);
const denormalizedData = denormalize(normalizedData.result, categories, normalizedData.entities);

console.log({ normalizedData });
console.log({ denormalizedData });

const normalizedData2 = normalize(subCategoriesData, subcategories);
const denormalizedData2 = denormalize(normalizedData2.result, subcategories, normalizedData2.entities);

console.log({ normalizedData2 });
console.log({ denormalizedData2 });

denormalizedData2的输出为

{id: 1, name: "sub-category-a", category: 1},
...

我原本希望是:

{id: 1, name: "sub-category-a", category: { id: 1, name: 'category-1' } },
...

如何使用normalizr实现目标?

1 个答案:

答案 0 :(得分:1)

老问题,但以防万一有人需要答案。 你的架构是错误的。 而不是

<块引用>

const subcategory = new schema.Entity('subCategories');

你应该写

<块引用>

const subcategory = new schema.Entity('subCategories', { category: category });

这意味着子类别具有由 category 架构描述的属性 category