我对normalizer还很陌生,还不能很好地理解它。如何规范化以下JSON响应,以便将其用于Redux:
{
"statusCode":200,
"message":"Random quotes",
"pagination":{
"currentPage":1,
"nextPage":null,
"totalPages":1
},
"totalQuotes":1,
"data":[
{
"_id":"5eb17aadb69dc744b4e70e05",
"quoteText":"One crowded hour of glorious life is worth an age without a name.",
"quoteAuthor":"Walter Scott",
"quoteGenre":"age",
"__v":0
}
]
}
将数据对象放在规范化对象的顶层会很有用。如何将其与TypeScript相结合?提前谢谢。
Typescript类型绝对可以帮助您理解正在处理的数据。您需要用不同的响应类型来描述它们,然后将它们拼凑在一起。
interface Quote {
_id: string;
quoteText: string;
quoteAuthor: string;
quoteGenre: string;
__v: number;
}
interface Pagination {
currentPage: number;
nextPage: null | number; // what is this when it's not null?
totalPages: number;
}
interface APIResponse {
statusCode: number;
message: string;
pagination: Pagination;
totalQuotes: number;
data: Quote[];
}
normalizr
在这里没有太大帮助,因为您只有一个实体类型,即Quote
。从某种意义上说,如果将响应本身视为一个实体,则有两种实体类型。但我不确定你将如何从中提取一个唯一的id。你可能需要根据API路径/参数自己添加它,因为JSON中缺少这些信息。
const quote = new schema.Entity("quote", {}, { idAttribute: "_id" });
const response = new schema.Entity("response", {
data: [quote] // an array of quote entities
});
console.log(normalize({...json, id: "/random-quote"}, response));
这会给你
{
"entities": {
"quote": {
"5eb17aadb69dc744b4e70e05": {
"_id": "5eb17aadb69dc744b4e70e05",
"quoteText": "One crowded hour of glorious life is worth an age without a name.",
"quoteAuthor": "Walter Scott",
"quoteGenre": "age",
"__v": 0
}
},
"response": {
"/random-quote": {
"statusCode": 200,
"message": "Random quotes",
"pagination": {
"currentPage": 1,
"nextPage": null,
"totalPages": 1
},
"totalQuotes": 1,
"data": ["5eb17aadb69dc744b4e70e05"],
"id": "/random-quote"
}
}
},
"result": "/random-quote"
}