我试图从redux状态反规范化一些数据,但我不能让它工作 . 我已经尝试过以我能想到的各种方式组合denormalize函数 . 这是一个猜谜游戏,到目前为止还没有任何工作 .
首先,我将产品数据标准化并将其置于状态 . 实体正在 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
}
}
因此,有一个属性“产品”包括所有实体,并且“产品”实体还有另一个“产品” .
规范化工作没有问题:
normalize(data, [productSchema]);
“productSchema”的定义如下:
productSchema = new schema.Entity('products', {
attributes: [attributeSchema],
things: [thingsSchema],
//+ other stuff
});
现在我想对产品进行非规范化,例如9 .
我在视图组件中使用“connect”来调用此函数以从状态检索数据并对其进行非规范化:
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"或上述错误 .
Edit :发现错误 - 在下面添加了它
1 回答
我发现错误 - 我的一个模式是错误的:我创建了
new schema.Entity('shippingZones')
但是在reducer中我将它添加到具有不同名称的状态:所以它正在寻找"shippingZones"而我只有"shipping_zones" . 所以我把它改成
new schema.Entity('shipping_zones')
和shipping_zones: action.payload.shipping_zones
遗憾的是
TypeError: entities[schemaKey] is undefined
消息无法指定"shippingZones",然后我可以节省几天时间 .所以这段代码到底有效: