如何解决带有嵌套对象数组的 Redux 的 Normalizr
我刚刚开始在 Redux 中使用 normalizr,但我无法让它工作。 即使我可以用普通的 JavaScript 做到这一点。
const data = [
{
data_detail: [
{
category: 'newCategory',_id: '123',},],_id: 'abc_id',customer: {
_id: '456',email: 'hello@gmail.com',name: 'Bob',date: '2021-01-10T01:51:24.387Z',];
我需要将其转换为
const normalizedResponse = {
customers: {
'456': {
_id: '456',details: {
'123': {
category: 'newCategory',orders: {
'abc_id: {
order_detail: [123],customer: '456',};
第 1 步:仅显示 orders
我做什么:
const userSchema = new schema.Entity(
'orders',);
const userListSchema = new schema.Array(userSchema);
const normalizedData = normalize(data,userListSchema);
我得到了什么
{
"entities": {
"orders": {
"abc_id": {
"data_detail": [
{
"category": "newCategory","id": "123"
}
],"id": "abc_id","customer": {
"id": "456","email": "hello@gmail.com","name": "Bob"
},"date": "2021-01-10T01:51:24.387Z"
},"abc_id-02": {
"data_detail": [
{
"category": "newCategory1","id": "123-02"
}
],"id": "abc_id-02","customer": {
"id": "456-02","date": "2001-01-10T01:51:24.387Z"
}
}
},"result": [
"abc_id","abc_id-02"
]
}
我想得到的:
orders: {
'abc_id: {
order_detail: [123],
解决方法
您的 data
对象中有 3 种不同的实体类型。首先为他们每个人起草一个schema
:
const detail = new schema.Entity('details');
const customer = new schema.Entity('customers');
const order = new schema.Entity('orders');
然后返回并填写关系。看起来 order
是最外面的实体。 order
包含一个 details
/categories
数组和一个 customer
。
const order = new schema.Entity('orders',{
data_detail: [detail],customer,});
您的所有实体都使用 _id
而不是 id
,因此您需要设置 idAttribute
。
您的 data
是 array
的 order
。您可以使用 new schema.Array(order)
,但也可以只使用 [order]
。
这是您的最终代码:
const customer = new schema.Entity("customers",{},{ idAttribute: "_id" });
const detail = new schema.Entity("details",{ idAttribute: "_id" });
const order = new schema.Entity(
"orders",{
data_detail: [detail],customer
},{ idAttribute: "_id" }
);
const normalizedData = normalize(data,[order]);
这给了你:
{
"entities": {
"details": {
"123": {
"category": "newCategory","_id": "123"
}
},"customers": {
"456": {
"_id": "456","email": "hello@gmail.com","name": "Bob"
}
},"orders": {
"abc_id": {
"data_detail": ["123"],"_id": "abc_id","customer": "456","date": "2021-01-10T01:51:24.387Z"
}
}
},"result": ["abc_id"]
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。