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

标签 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 的最佳实践中管理它?

最佳答案

查看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/

相关文章:

javascript - react Mocha - `Missing class properties transform`

javascript - 将参数传递给无状态功能组件中的事件函数

reactjs - .map() 不执行任何操作并且没有错误 - react

Redux 等待异步操作完成

javascript - Redux-form:在页面顶部显示错误列表

reactjs - 如何使用 Material ui 处理快速拨号操作?

javascript - 不包含名为

javascript - 使用 ReactJS 从兄弟组件调用方法

javascript - 在 redux 状态树中添加新数据

javascript - 如何在特定条件下使用react隐藏和显示