【问题标题】:Denormalize with normalizr用 normalizr 去规范化
【发布时间】:2018-10-19 17:39:28
【问题描述】:

我正在尝试对来自 redux 状态的一些数据进行非规范化处理,但我无法让它工作。我已经尝试以我能想到的所有方式组合非规范化函数。这是一个猜谜游戏,到目前为止没有任何效果。

首先我将产品数据归一化并放入状态。 实体被放入state.data.products,包括产品。

state.data: {

    products: {
          products: {
                 9:   {
                     id: 9
                     attributes: [ 10, 45, 23 ],
                     things: [23, 55, 77]
                  },

                 11     //etc 

            } 
           attributes: {

                10: {
                   id: 10
                },

                45:    //etc
            },

            things: {   //etc

     }
   }

所以有一个属性“products”包含所有实体,而“products”实体还有另一个“products”。

标准化工作没有问题:

normalize(data, [productSchema]);

“productSchema”的定义如下:

productSchema = new schema.Entity('products', {
    attributes: [attributeSchema],
    things: [thingsSchema],
    //+ other stuff
});

现在我想对一个产品进行非规范化,例如 9。

我在视图组件中使用“连接”来调用此函数以从状态中检索数据并对其进行非规范化:

export const denormalizeProduct = (state, productId) => {
      const entities = state.data.products;

    return denormalize( 
            productId, 
            [productSchema],
            entities
    );
}

如果我打电话给 denormalizeProductById(state, 9) ,我只会得到 9 回来。 (类似于 question ,但我无法从中找到解决方案,它将两个示例混合在一起)

如果我把“productSchema”不带数组:

return denormalize( 
            productId, 
            productSchema,
            entities
    );

我收到错误:TypeError: entities[schemaKey] is undefined。 我尝试过的所有操作都会导致“9”或上述错误。


编辑: 发现错误 - 在下面添加它

【问题讨论】:

  • 它应该是不带括号的productSchema,因为您没有对数组进行非规范化。重新选择的东西与问题有什么关系吗?如果没有,如果您在此处删除它会更清楚,而是添加所有代码以获得最小的完整示例(即剥离但完整定义 entities 和 productSchema 加上失败的 denormalize 调用)。
  • 我去掉了重选功能,还是一样的问题。

标签: redux denormalization normalizr


【解决方案1】:

我发现了错误 - 我的架构之一是错误的:我创建了 new schema.Entity('shippingZones') 但在减速器中我将它添加到具有不同名称的状态:

shipping_zones: action.payload.shippingZones

所以它在寻找“shippingZones”,而我猜只有“shipping_zones”。所以我把它改成了new schema.Entity('shipping_zones')和shipping_zones: action.payload.shipping_zones

可惜TypeError: entities[schemaKey] is undefined的消息不能指定“shippingZones”,那我可以节省几天时间。

所以这段代码最终起作用了:

const entities = state.data.products; 

return denormalize( 
        productId, 
        productSchema,
        entities
);

【讨论】:

    猜你喜欢
    • 2016-06-10
    • 2017-06-23
    • 2018-05-23
    • 2016-06-21
    • 2021-05-22
    • 2018-04-09
    • 2018-03-05
    • 2019-03-24
    • 2021-08-13
    相关资源
    最近更新 更多