我有一个非常标准的嵌套JSON响应。 项目有许多信息中心。 信息中心有许多图表。
定义和使用我的模式的正确方法是什么?
以下是我的Schemas.js的代码,我的API响应以及Normalizr将我的API响应转换为。
Schemas.js:
import { Schema, arrayOf, normalize } from 'normalizr';
// Create a schema for each model.
const project = new Schema('projects');
const dashboard = new Schema('dashboard');
const chart = new Schema('chart');
// Projects have many dashboards.
project.define({
dashboards: arrayOf(dashboard)
});
// Dashboards have many charts.
dashboard.define({
charts: arrayOf(chart)
});
export const Schemas = { project, dashboard, chart };
我的API响应:
{
projects: [{
id: 1,
name: "Project 1",
dashboards: [{
id: 1,
name: "Dashboard 1",
charts: [{
id: 1,
name: "Chart 1"
},
{
id: 2,
name: "Chart 2"
}]
},
{
id: 2,
name: "Dashboard 2",
charts: [{
id: 3,
name: "Chart 3"
},
{
id: 4,
name: "Chart 4"
}]
}]
},
{
id: 2,
name: "Project 2",
dashboards: [{
id: 3,
name: "Dashboard",
charts: []
}]
}]
}
当我在动作中收到此JSON时,我会normalize(response, Schemas.project);
。这似乎将整个回复转移到entities.projects.undefined
。
{
entities: {
projects: {
undefined: {
projects: [{
id: 1,
name: "Project 1",
...
}, ...]
}
}
},
result: undefined
}
我应该如何正确定义和使用我的模式?
参考文献:
https://github.com/gaearon/normalizr
https://github.com/reactjs/redux/blob/master/examples/real-world/actions/index.js
答案 0 :(得分:5)
这应该会给你想要的结果:
normalize(response, {
projects: arrayOf(Schemas.project)
});
项目键是必需的,因为你的响应中有一个额外的键,而arrayOf()表示API返回一个结果数组。