我有一个非常标准的嵌套 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