【发布时间】:2020-04-24 08:41:17
【问题描述】:
我有这个来自 API 的响应...
{
"current_page": 1,
"data": [
{
"id": 1,
"category_id": 1,
"creator_id": 1,
"instructor_id": 1,
"difficulty_id": 1,
"status_id": 1,
"title": "hebae",
"overview": "Course Overview",
"deleted_at": null,
"created_at": "2020-01-02 15:16:08",
"updated_at": "2020-01-02 15:16:08"
},
{
"id": 2,
"category_id": 1,
"creator_id": 1,
"instructor_id": 2,
"difficulty_id": 1,
"status_id": 1,
"title": "update course 1",
"overview": "Course Overview",
"deleted_at": null,
"created_at": "2020-01-02 15:18:40",
"updated_at": "2020-01-02 15:19:06"
},
{
"id": 3,
"category_id": 1,
"creator_id": 1,
"instructor_id": 1,
"difficulty_id": 1,
"status_id": 1,
"title": "hebaTest",
"overview": "Course Overview",
"deleted_at": null,
"created_at": "2020-01-02 15:24:09",
"updated_at": "2020-01-02 15:24:09"
},
{
"id": 4,
"category_id": 2,
"creator_id": 1,
"instructor_id": 1,
"difficulty_id": 1,
"status_id": 1,
"title": "hebaTest",
"overview": "Adile",
"deleted_at": null,
"created_at": "2020-01-02 15:25:03",
"updated_at": "2020-01-02 15:25:03"
},
{
"id": 5,
"category_id": 2,
"creator_id": 1,
"instructor_id": 1,
"difficulty_id": 1,
"status_id": 1,
"title": "hebaTest",
"overview": "Adile",
"deleted_at": null,
"created_at": "2020-01-02 15:33:06",
"updated_at": "2020-01-02 15:33:06"
},
{
"id": 6,
"category_id": 1,
"creator_id": 1,
"instructor_id": 1,
"difficulty_id": 1,
"status_id": 1,
"title": "Course Title",
"overview": "Course Overview",
"deleted_at": null,
"created_at": "2020-01-05 08:24:56",
"updated_at": "2020-01-05 08:24:56"
},
],
"first_page_url": "http://skillboardbackend-staging.zph2jwe3pc.eu-west-1.elasticbeanstalk.com/api/course?page=1",
"from": 1,
"last_page": 2,
"last_page_url": "http://skillboardbackend-staging.zph2jwe3pc.eu-west-1.elasticbeanstalk.com/api/course?page=2",
"next_page_url": "http://skillboardbackend-staging.zph2jwe3pc.eu-west-1.elasticbeanstalk.com/api/course?page=2",
"path": "http://skillboardbackend-staging.zph2jwe3pc.eu-west-1.elasticbeanstalk.com/api/course",
"per_page": 15,
"prev_page_url": null,
"to": 15,
"total": 29
}
我正在尝试将“数据”数组定义为“类别”对象,其余数据可以保持不变,如何使用 normalizr 做到这一点?
我试过这个...
const { data } = await apiGetAllCategories();
const dataSchema = new schema.Entity("categories");
const coursesSchema = new schema.Entity("info", {
data: [dataSchema]
});
const normalizedData = normalize(data, coursesSchema);
console.log(normalizedData);
但它总是给我未定义的“信息”,而未定义的“结果”...
我在这里做错了什么?
【问题讨论】:
-
以上 API 响应似乎没有那么深的嵌套,它需要额外的库来提取任何数据。向我们展示所需的输出数据样本,我很确定有一个简单的 vanilla js 解决方案可供建议。
-
@YevgenGorbunkov 我只需要与响应相同的结构,除了数据是对象而不是数组,并且该对象的键是 id,就像我从“ normalizr”在屏幕截图的“类别”中。