【问题标题】:Normalizr create result for single enityNormalizr 为单个实体创建结果
【发布时间】:2016-12-14 06:15:33
【问题描述】:

我正在使用 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 标准化为数组,但也许有更好的方法来做到这一点?

【问题讨论】:

    标签: redux normalizr


    【解决方案1】:

    在我的应用程序中,我针对这种情况使用了两种不同的操作,FETCH_POSTFETCH_POSTS 相应地。

    但是如果你有一些问题,你可以使用一些小技巧:

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

    当规范化单个帖子项目时,我们可以简单地将其包装成数组并将其规范化为帖子数组。

    【讨论】:

    • 谢谢,成功了!我不想有两个完全相同的动作。它使我的减速器缩短了两倍。
    猜你喜欢
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多