Normalizr为单个enity创建结果

jus*_*ris 0 redux normalizr

我使用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
}
*/
Run Code Online (Sandbox Code Playgroud)

然后我想处理归一化的反应,无论它是怎么来的.

但问题是,对于单个项目而言,我得到的result: 1不是数组result: [1],而是在后来的代码中导致了一些问题.

现在我必须result手动规范化数组,但也许有更好的方法可以做到这一点?

1ve*_*ven 6

在我的应用程序中,我对此案例使用了两种不同的操作,FETCH_POSTFETCH_POSTS相应地.

但如果你有一些问题,你可以使用一点点黑客:

const singleResponse = {id: 1, text: 'post one'};
normalize([singleResponse], posts);
Run Code Online (Sandbox Code Playgroud)

规范化单个帖子项目时,我们可以简单地将其包装到数组中并将其标准化为帖子数组.