【问题标题】:Normalizr schema : nested entities does not become normalizedNormalizr 模式:嵌套实体不会被规范化
【发布时间】:2018-10-10 01:19:18
【问题描述】:

我有一个实体“term_attributes”,其中包含两个未标准化的嵌套实体。我使用 normalizr: "^3.2.2"。

原始数据是一个产品数组,这里是相关位:

[{
        "id": 9, 
        "price": "184.90",
        "term_attributes": [ 
        {
                "id": 98,
                "attribute": {
                    "id": 1,
                    "name": "Color",
                    "slug": "color"
                },
                "term": {
                    "id": 94,
                    "name": "Bags",
                    "slug": "bags"
                }
            }, 

规范化代码:

export const termSchema = new schema.Entity('terms');
export const attributeSchema = new schema.Entity('attributes');

export const termAttributeSchema = new schema.Entity('term_attributes', { idAttribute: 'id'},{
    attribute: attributeSchema,
    term: termSchema
});

export const termAttributeListSchema = new schema.Array(termAttributeSchema);

export const productSchema = new schema.Entity('products', {
    term_attributes: termAttributeListSchema,
});

编辑:忘记添加 productListSchema(虽然不重要):

export const productListSchema = new schema.Array(productSchema);

Term_attributes 是标准化的,但不是它的嵌套实体(attributesterms)。结果如下:

{
    "entities": {
"27": {
     "id": 27, 
     "price": "184.90",
     "term_attributes": [105, 545, 547, 2, 771]
},

"term_attributes": {

            "2": {
                "id": 2,
                "attribute": {
                    "id": 1,
                    "name": "Color",
                    "slug": "color"
                },
                "term": {
                    "id": 2,
                    "name": "Fashion",
                    "slug": "fashion"
                }
            },

如果我从 termAttributeSchema 中删除“idAttribute”,则规范化失败:

export const termAttributeSchema = new schema.Entity('term_attributes', {
    attribute: attributeSchema,
    term: termSchema
});

^^ 怎么了?

更新

下面的 Paul Armstrongs 解决方案有效,我只是跳过 termAttributeListSchema 而是使用 termAttributeSchema:term_attributes: termAttributeSchema

【问题讨论】:

    标签: redux normalizr


    【解决方案1】:

    您的productSchema 不正确。它应该明确声明term_attributes 是一个数组,可以通过两种方式完成:

    使用Array速记:

    export const productSchema = new schema.Entity('products', {
        term_attributes: [termAttributeListSchema]
    });
    

    或者使用schema.Array:

    export const productSchema = new schema.Entity('products', {
        term_attributes: new schema.Array(termAttributeListSchema)
    });
    

    【讨论】:

    • 我试过了,但结果是错误的——所以我跳过了“termAttributeListSchema”并直接调用了 termAttributeSchema:term_attributes:[termAttributeSchema]——但由于某种原因它失败了(?)
    • 现在它突然起作用了!...一定是一些临时问题
    猜你喜欢
    • 2018-05-23
    • 2017-12-16
    • 2021-05-22
    • 2016-11-15
    • 2018-04-09
    • 2017-07-20
    • 2018-11-26
    • 2018-10-19
    • 2017-06-21
    相关资源
    最近更新 更多