如何使用归一化来处理嵌套的标准化JSON API响应,这些响应是通过{ data: ... }标准实现的关键?
例如,一个Book
{
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,
}
}
}
} 如何设计模式来处理嵌套的数据键?
发布于 2016-07-04 16:58:34
我相信您所追求的是assignEntity函数的使用,它可以在normalize的选项中传递。在这个例子中,它允许我们在适当的情况下过滤掉冗余的data属性,并直接到下面的值。
实际上,assignEntity让我们控制数据的每个键是如何标准化的。请看一下这里,了解它是如何工作的。
我把这些放在一起作为一个演示,看看:http://requirebin.com/?gist=b7d89679202a202d72c7eee24f5408b6。这里有一个片段:
book.define({
data: {
publisher: publisher,
author: author,
characters: normalizr.arrayOf(character)
}}
);
publisher.define({
data: {
country: country
}
});
const result = normalizr.normalize(response, book, { assignEntity: function (output, key, value, input) {
if (key === 'data') {
Object.keys(value).forEach(function(d){
output[d] = value[d];
})
} else {
output[key] = value;
}
}});还可以特别看到Ln 29,其中characters的数组有一些对象,其信息嵌套在data中,有些则没有。所有都被正确地标准化了。
我还添加了一些部分来演示它如何处理数组和深度嵌套的数据,请参阅publisher中的publisher模型。
使用所提供的数据,由于缺少id,您将需要一个片段,每个模式都包含在示例中。
Normalizr太棒了,我希望这能更好地解释它:)
发布于 2016-07-01 14:24:18
对于响应中的每个实体,您应该创建自己的模式。
在您的示例中,我们有三个实体-- books、authors和publishers
// schemas.js
import { Schema } from 'normalizr';
const bookSchema = new Schema('book');
const publisherSchema = new Schema('publisher');
const authorSchema = new Schema('author');如果某个实体包含应该规范化的嵌套数据,则需要使用define方法,schema.This方法接受具有嵌套规则的对象。
如果我们需要规范化publisher和book实体的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);https://stackoverflow.com/questions/38147224
复制相似问题