結賬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
鍵告訴你,你已經收到一個收集與1的ID從那裏你可以索引到entities
關鍵,這已被夷爲平地的ID 。有關如何在調度程序中使用該功能的更多信息,請查看https://github.com/gaearon/normalizr#explanation-by-example。免責聲明:我沒有使用normalizr,但是由於它是由Dan Abramov(Redux的作者)編寫的,我認爲你會很好的掌握。
您可能會對這裏的Redux的作者的一個類似問題的答案感興趣:http://stackoverflow.com/questions/33940015/how-to-choose-the-redux-state-shape-for-an -app-與一覽細節的視圖 - 和 - pagina/33946576#33946576 –