Normalizr v3.2.2中嵌套实体未实现标准化问题求助
搞定normalizr 3.2.2的嵌套实体标准化问题
嘿,我来帮你梳理这个normalizr的标准化需求!先看你提供的原始数据结构(我补全了片段):
[ { "id": 9, "price": "184.90", "term_attributes": [ { "id": 98, "attribute": { "id": 1, "name": "Color", "slug": "color" }, "term": { "id": 94, "name": "Bags", "slug": "bags" } } // 更多属性项... ] } // 更多商品... ]
你的问题核心是term_attributes里的attribute和term这两个嵌套实体没被正确标准化,对吧?下面是完整的解决方案:
完整标准化代码
import { schema, normalize } from 'normalizr'; // 先定义最基础的子实体Schema export const attributeSchema = new schema.Entity('attributes'); export const termSchema = new schema.Entity('terms'); // 定义term_attribute的Schema,关联它的两个嵌套实体 export const termAttributeSchema = new schema.Entity('termAttributes', { attribute: attributeSchema, term: termSchema }); // 定义商品Schema,关联term_attributes数组 export const productSchema = new schema.Entity('products', { term_attributes: [termAttributeSchema] }); // 最后对商品数组执行标准化 const normalizedData = normalize(yourProductArray, [productSchema]);
几个关键细节要注意
- 每个嵌套的实体都得单独声明
schema.Entity,然后在父实体的Schema里明确指定关联字段。 - 如果关联的是数组(比如
term_attributes),一定要用[schema]的格式来标记,normalizr才会识别为数组类型的实体集合。 - 标准化后的结果会分成两部分:
entities:里面会有products、termAttributes、attributes、terms四个对象,每个对象以实体ID为键,存储对应的数据,实现了实体的统一管理。result:就是原始商品数组对应的ID列表,方便你快速引用实体。
这样处理后,所有嵌套的未标准化实体就都被正确提取并标准化啦!
内容的提问来源于stack exchange,提问作者Galivan
相关产品推荐
相关产品推荐

