如何获得最佳实践React Redux嵌套数组数据?

时间:2016-01-25 15:09:17

标签: reactjs redux

我的数据看起来像这样:

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

包含3个级别项目的对象数组。

我如何在redux的最佳实践中管理它?

1 个答案:

答案 0 :(得分: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密钥告诉您已收到一个ID为1的集合。从那里,您可以索引entities密钥,该密钥已被id展平。有关如何在调度程序中使用此功能的更多信息,请查看https://github.com/gaearon/normalizr#explanation-by-example

免责声明:我没有使用过normalizr,但由于它是由Dan Abramov(Redux的作者)编写的,我认为你会得到很好的帮助。