Normalizr 为单个实体创建结果
Normalizr create result for single enity
我正在使用 Normalizr 从不同的 API 端点获得相同的响应形状。
const post = new Schema('posts');
const posts = arrayOf('post');
const listResponse = [
{id: 1, text: 'post one'},
{id: 2, text: 'post two'},
];
normalize(listResponse, posts);
/*
{
entities: {
posts: {
1: {id: 1, text: 'post one'},
2: {id: 2, text: 'post two'}
}
},
result: [1, 2]
}
*/
const singleResponse = {id: 1, text: 'post one'};
normalize(singleResponse, post);
/*
{
entities: {
posts: {
1: {id: 1, text: 'post one'}
}
},
result: 1
}
*/
那不管怎么来的我都想把归一化的反应治疗一下
但问题是,对于单个项目,我得到的是 result: 1
而不是数组 result: [1]
,这会导致我以后的代码出现一些问题。
现在我必须将 result
规范化为手动排列,但也许有更好的方法来做到这一点?
在我的应用程序中,我针对这种情况使用了两种不同的操作,相应地 FETCH_POST
和 FETCH_POSTS
。
但是如果你有一些问题,你可以使用一些技巧:
const singleResponse = {id: 1, text: 'post one'};
normalize([singleResponse], posts);
当规范化单个 post 项目时,我们可以简单地将其包装到数组并将其规范化为 posts 的数组。
我正在使用 Normalizr 从不同的 API 端点获得相同的响应形状。
const post = new Schema('posts');
const posts = arrayOf('post');
const listResponse = [
{id: 1, text: 'post one'},
{id: 2, text: 'post two'},
];
normalize(listResponse, posts);
/*
{
entities: {
posts: {
1: {id: 1, text: 'post one'},
2: {id: 2, text: 'post two'}
}
},
result: [1, 2]
}
*/
const singleResponse = {id: 1, text: 'post one'};
normalize(singleResponse, post);
/*
{
entities: {
posts: {
1: {id: 1, text: 'post one'}
}
},
result: 1
}
*/
那不管怎么来的我都想把归一化的反应治疗一下
但问题是,对于单个项目,我得到的是 result: 1
而不是数组 result: [1]
,这会导致我以后的代码出现一些问题。
现在我必须将 result
规范化为手动排列,但也许有更好的方法来做到这一点?
在我的应用程序中,我针对这种情况使用了两种不同的操作,相应地 FETCH_POST
和 FETCH_POSTS
。
但是如果你有一些问题,你可以使用一些技巧:
const singleResponse = {id: 1, text: 'post one'};
normalize([singleResponse], posts);
当规范化单个 post 项目时,我们可以简单地将其包装到数组并将其规范化为 posts 的数组。