我有如下所示的数据:
{[{id: "1",
stories: [{
id: "11",
items: [{ id:"111", title:"bla bla" },{ id:"222", title:"bla bla" },{ id:"333", title:"bla bla" }]
}]
它的对象数组具有 3 个级别的项目。
我如何在 redux 的最佳实践中管理它?
最佳答案
查看 https://github.com/gaearon/normalizr 。它允许您将嵌套数据描述为模式的集合。对于您的示例,我认为您可以使用:
import { normalize, Schema, arrayOf } from 'normalizr';
const collection = new Schema('collections');
const story = new Schema('stories');
const item = new Schema('items');
collection.define({
stories: arrayOf(story)
});
story.define({
items: arrayOf(item)
})
// i'm not sure what your outer result type is, so i've
// just named it 'collection'
const collections = [{id: "1",
stories: [{
id: "11",
items: [{ id:"111", title:"bla bla" },{ id:"222", title:"bla bla" },{ id:"333", title:"bla bla" }]
}]
}]
const normalized = normalize(collections, arrayOf(collection));
/* normalized === {
"entities": {
"collections": {
"1": {
"id": "1",
"stories": [
"11"
]
}
},
"stories": {
"11": {
"id": "11",
"items": [
"111",
"222",
"333"
]
}
},
"items": {
"111": {
"id": "111",
"title": "bla bla"
},
"222": {
"id": "222",
"title": "bla bla"
},
"333": {
"id": "333",
"title": "bla bla"
}
}
},
"result": [
"1"
]
} */
result
键告诉您收到了一个 id 为 1 的集合。从那里您可以索引到 entities
键,该键已被 id 扁平化。有关如何在调度程序中使用它的更多信息,请查看 https://github.com/gaearon/normalizr#explanation-by-example 。免责声明:我没有使用 normalizr,但由于它是由 Dan Abramov(Redux 的作者)编写的,我认为你会得到很好的帮助。
关于reactjs - 如何获得最佳实践 React Redux 嵌套数组数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34995822/