首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获得最佳实践-- Redux嵌套数组数据?

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

Stack Overflow用户
提问于 2016-01-25 15:09:17
回答 1查看 1.4K关注 0票数 4

我有这样的数据:

代码语言:javascript
复制
{[{id: "1",
stories: [{
    id: "11",
    items: [{ id:"111", title:"bla bla" },{ id:"222", title:"bla bla" },{ id:"333", title:"bla bla" }]
}]

它的对象数组包含三个级别的项。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-25 16:23:23

看看https://github.com/gaearon/normalizr。它允许您将嵌套数据描述为架构的集合。以你为例,我认为你可以:

代码语言:javascript
复制
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 (“Redux”的作者)编写的,所以我认为您会得到很好的控制。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34995822

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档