假设一个用户已经收藏了许多猫,当被要求提供用户的收藏时,api端点会给出一个猫列表:
const catsList = [{id:1,name:"catA"},{id:2,name:"catB"},{id:3,name:"catC"}];
// ex: GET http://app.com/api/favorites => results in following json
{favorites:[{id:2,name:"catB"},{id:3,name:"catC"}]}
// the result is the list of cats
//and normalizr schema
const cats = new Schema('cats');
const favorites = new Schema('favorites');
现在我的问题是,我将如何规范化这些实体,以便我得到以下结果,
entities.favorites=[2,3]; //2 and 3 are cats
entities.cats=[{id:1,name:"a"},{id:2,name:"b"},{id:3,name:"c"}];
我将如何使用normalizr完成此操作?
答案 0 :(得分:0)
像
这样的东西const cats = new Schema('cats');
const response = {
favorites: [{
id: 2,
name: "catB"
}, {
id: 3,
name: "catC"
}]
}
const normalized = normalize(response, {
favorites: arrayOf(cats)
})
normalized
值将类似于
{
result: {
favorites: [2, 3]
},
entities: {
cats: {
2: {
id: 2,
name: "catB"
}, {
id: 3,
name: "catC"
}
}
}
}
normalized.entities
是一个对象而不是一个数组实际上非常重要 - 否则按ID查询会很慢。
此时,无论如何,您都可以随意转换此表示形式。