【问题标题】:Normalizing not nested tree into nested with Normalizr使用 Normalizr 将非嵌套树规范化为嵌套
【发布时间】:2016-11-15 23:35:12
【问题描述】:

我必须规范化来自服务器的两个响应,并使用 normalizr 将它们存储在我的商店中。 第一个回复给了我部分,第二个回复给了我帖子。 版块有很多帖子一篇文章只能有一个版块

第一反应(部分):

[
  {
    id: 10,
    title: "foo"
  },
  ...
]

第二次回复(帖子):

[
  {
    id: 2,
    sid: 10, //id of the section
    title: "foo",
    text: "foo foo"
  },
  ...
]

我想将响应标准化为这个架构:

{
  entities: {
    sections: {
      10: {title: "foo", posts: [2, 5, 12, 152]},
      15: {title: "example", posts: [1, 8]},
      ...
    },
    posts: {
      1: {id: 1, sid: 15, title: "abc", text: "something"},
      2: {id: 2, sid: 10, title: "foo", text: "foo foo"},
      ...
    }
  }
}

由于响应不是嵌套的,我不知道如何定义模式。

【问题讨论】:

    标签: javascript reactjs redux normalizr


    【解决方案1】:

    也许你可以用简单的代码做到这一点?没有任何图书馆? oO

    var posts = [ ... ]; // some posts here
    var sections = [ ... ]; // some sections here
    var schema = { entities: { sections: {}, posts: {} } };
    
    for (var i = 0; i < sections.length; i++) {
        var section = sections[i];
        schema.entities.sections[section.id] = {
            title: section.title,
            posts: []
        }
    }
    
    for (var j = 0; j < posts.length; j++) {
        var post = posts[j];
        schema.entities.posts[post.id] = post;
        schema.entities.sections[post.sid].posts.push(post.id);
    }
    

    【讨论】:

    • 这是一个很好的答案。 Normalizr 用于处理需要去嵌套的单个 JSON 对象。您必须首先将您的响应组合在一起,然后通过 normalizr 运行它。这个答案是一个更简单的解决方案。
    • @PaulArmstrong 好吧,实际上在非规范化时它是有意义的。我们有一个 rest api,我们的 JSON 没有深度嵌套,但我们更喜欢我们的 react 组件中的非规范化对象。有一些通用的方法会很棒
    猜你喜欢
    • 2018-05-23
    • 2018-04-09
    • 2021-05-22
    • 2018-11-26
    • 2018-10-10
    • 2020-05-06
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    相关资源
    最近更新 更多