2016-01-25 62 views
2

我看起來像這樣的數據:如何獲得最佳實踐React Redux嵌套數組數據?

{[{id: "1", 
stories: [{ 
    id: "11", 
    items: [{ id:"111", title:"bla bla" },{ id:"222", title:"bla bla" },{ id:"333", title:"bla bla" }] 
}] 

它有3個級別的項目對象的數組。

我如何在redux的最佳實踐中管理它?

+0

您可能會對這裏的Redux的作者的一個類似問題的答案感興趣:http://stackoverflow.com/questions/33940015/how-to-choose-the-redux-state-shape-for-an -app-與一覽細節的視圖 - 和 - pagina/33946576#33946576 –

回答

3

結賬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的作者)編寫的,我認爲你會很好的掌握。