本文介绍了如何使用 Normalizr 在 redux 中标准化状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个嵌套的对象数组,如下所示:
I have a nested array of objects like this:
var posts = [
{
_id:1234,
body:"text",
comments:[
{
_id:234,
body:"hello world", {
]
},
{
_id:434,
body:"hello world",
replies:[
{
_id:0e2345,
body:"hello",
{
]
}
]
}
]
我想使用 normalizr 来简化数组并与 redux 一起使用.我已经阅读了 Normalizr 文档,但它的例子很少,我不知道我做错了什么.
I want to use normalizr to simplify array and use with redux. I have read the Normalizr documentation but it has few examples and I do not know what I am doing wrong.
我尝试了以下代码但没有成功.我得到的结果是一个未定义的数组.
I have tried the following code without success. The result I get is an array with undefined.
export function getPosts(state, action) {
const { payload } = action;
const { data} = payload;
const normalized = new schema.Entity("posts", {}, { idAttribute: "_id",});
const normalizedData = normalize(data, [normalized]);
return {
...state,
normalizedData,
};
}
我需要这样的东西:
entities:{
posts:{
123:{
_id:123,
body:"hello world",
comments:{
234:{
_id:234,
body:"hello world",
replies:{
0e2345:{
_id:0e2345,
body:"oh no"
}
}
}
}
}
}
}
推荐答案
我已尝试使用 JSON 对象重现此问题:
I've tried to reproduce this using a JSON object:
[{
"_id":1234,
"body":"text",
"comments":[
{
"_id":234,
"body":"hello world" }
]
},
{
"_id":434,
"body":"hello world",
"replies":[
{
"_id":0e2345,
"body":"hello"
}
]
}
]
并在代码中制作结构:
import data from "./data.json";
import { normalize, schema } from "normalizr";
const _id = new schema.Entity('_id');
const body = new schema.Entity('body');
const normalized = new schema.Entity("posts", {
posts:{
_id:{
_id:_id,
body:body,
comments:{
_id:{
_id:_id,
body:body,
replies:{
_id:{
_id:_id,
body:body
}
}
}
}
}
}
});
const normalizedData = normalize(data, [normalized]);
console.log(normalizedData);
我得到下一个 控制台输出.
这篇关于如何使用 Normalizr 在 redux 中标准化状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!