我有一个非常标准的嵌套JSON响应 . Projects 有很多 dashboards . Dashboards 有很多 charts .
定义和使用我的模式的正确方法是什么?
下面是我的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
}
我该如何正确定义和使用我的模式呢?
References:
https://github.com/gaearon/normalizr
https://github.com/reactjs/redux/blob/master/examples/real-world/actions/index.js
1 回答
这应该会给你想要的结果:
项目键是必需的,因为您的响应中有一个额外的键,而arrayOf()表示API返回一组结果 .