如何使用 normalizr处理嵌套标准化JSON API通过 { data: ... }
标准的关键响应?
例如书籍
{
data: {
title: 'Lord of the Rings',
pages: 9250,
publisher: {
data: {
name: 'HarperCollins LLC',
address: 'Big building next to the river',
city: 'Amsterdam'
},
},
author: {
data: {
name: 'J.R.R Tolkien',
country: 'UK',
age: 124,
}
}
}
}
我将如何设计架构来处理嵌套数据键?
最佳答案
对于响应中的每个实体,您应该创建它自己的架构。
在您的示例中,我们有三个实体 - books
、authors
和 发布者
:
// schemas.js
import { Schema } from 'normalizr';
const bookSchema = new Schema('book');
const publisherSchema = new Schema('publisher');
const authorSchema = new Schema('author');
如果某个实体包含嵌套数据,需要规范化,我们需要使用它的模式的define
方法。这个方法接受一个带有嵌套规则的对象。
如果我们需要规范化 book
实体的 publisher
和 author
属性,我们应该将一个对象传递给具有相同结构的 define
函数作为我们的回应:
// schemas.js
bookSchema.define({
data: {
publisher: publisherSchema,
author: authorSchema
}
});
现在我们可以规范化我们的响应:
import { normalize } from 'normalizr';
import { bookSchema } from './schemas.js';
const response = {
data: {
title: 'Lord of the Rings',
pages: 9250,
publisher: {
data: {
name: 'HarperCollins LLC',
address: 'Big building next to the river',
city: 'Amsterdam'
},
},
author: {
data: {
name: 'J.R.R Tolkien',
country: 'UK',
age: 124,
}
}
}
}
const data = normalize(response, bookSchema);
关于javascript - Redux normalizr - 嵌套的 API 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38147224/