ImmutableJS如何简化过滤器和更新逻辑 [英] ImmutableJS how to simplify a filter and update logic

查看:89
本文介绍了ImmutableJS如何简化过滤器和更新逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的数据结构

[
  {
    "id": 1,
    "title": "Welcome to my playground",
    "description": "This is so fun to play with, you will like it <3",
    "comments": [
      {
        "id": 1140406,
        "comment": "this is an example comment",
        "postId": 1
      }
    ]
  },
  ...
]

我正在尝试使用不可变的js来执行此操作

  1. 获取所有帖子
  2. 搜索要添加评论的帖子
  3. 找到帖子后添加评论

以下是我的代码

posts = posts.map((post) => {

            if(post.get('id') == payload.post_id) {

                return post.update('comments', (comments) => {    
                    return comments.push(Map({
                        id: payload.id,
                        comment: payload.comment
                    }));
                });
            }

            return post;
        });

但是我认为这种模式非常普遍,应该在immutableJS中采用一种更简单的方法.任何建议都会有所帮助,谢谢.

But I assume this pattern is very common and there should be a simpler way to do this in immutableJS. Any advice will be helpful, thanks.

推荐答案

对于其他有相同问题的人:应该考虑数据标准化(搜索normalizr).然后,您可以将数据规范化为:

For others who has the same question: One should consider a data normalisation (search for normalizr). You could then normalise your data to something like:

"entities": {
    "posts": {
        "1": {
            "id": 1,
            "title": "Welcome to my playground",
            "description": "This is so fun to play with, you will like it <3",
            "comments": [1140406, 1140407, 1140408]
        },
        "42" : {...}
    }
    "comments": {
        "1140406": {
            "id": 1140406,
            "comment": "this is an example comment",
            "postId": 1
        },
        "1140407": {...}
    }
}

然后更新帖子和评论变得更加容易

then updating post and comments becomes much easier

这篇关于ImmutableJS如何简化过滤器和更新逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆