【问题标题】:Best practice for deleting related entities in normalized state in ReduxRedux 中删除规范化状态下相关实体的最佳实践
【发布时间】:2018-08-29 13:23:47
【问题描述】:

当从规范化数据中删除一个实体时,我们如何处理删除被删除实体拥有的其他实体?比如下面的归一化数据,如果我要删除user1,我也要删除user1发的所有帖子和cmets。对于这种情况,是否有任何已知的方法或最佳做法?

{
    posts : {
        byId : {
            "post1" : {
                id : "post1",
                author : "user1",
                body : "......",
                comments : ["comment1", "comment2"]    
            }
        },
        allIds : ["post1"]
    },
    comments : {
        byId : {
            "comment1" : {
                id : "comment1",
                author : "user1",
                comment : ".....",
            },
            "comment2" : {
                id : "comment2",
                author : "user1",
                comment : ".....",
            },
        },
        allIds : ["comment1", "comment2"]
    },
    users : {
        byId : {
            "user1" : {
                username : "user1",
                name : "User 1",
            }
        },
        allIds : ["user1"]
    }
}

【问题讨论】:

标签: reactjs redux normalization


【解决方案1】:

您可以通过多种方式查看此内容:

  1. 每个元素的 reducer 负责为删除用户的任何操作清理数据,或者;
  2. 删除用户的操作具有删除多个关联项(或调度多个关联操作)的副作用

选项 1

假设您有如下操作:

  const deleteUser = userId => {
    return ({
      type: 'DELETE_USER',
      userId
    })
  }

user 的 reducer 可能如下所示:

  const users = (state = {}, action) => {

    switch (action.type) {
      case 'DELETE_USER':
        // delete user logic
        break;
    }

  }

从技术上讲,Redux 中没有任何东西可以阻止您对 postscomments 减速器中的 DELETE_USER 操作做出反应:

  const posts = (state = {}, action) => {
    const newState = Object.assign({}, state);
    switch (action.type) {
      case 'DELETE_USER':
        // delete posts for action.userId
        break;
    }
  }

选项 2

如果您不喜欢上述内容,并且希望保持一定程度的关注点分离,那么请考虑寻找一种触发与操作相关的副作用的方法,例如 redux-sagaredux-thunk

实现会因库而异,但想法是:

  1. 收听DELETE_USER 操作
  2. 触发一些操作以:
    1. 删除用户 (DELETE_USER)
    2. 删除用户的帖子 (DELETE_USER_POSTS)
    3. 为用户删除 cmets (DELETE_USER_COMMENTS)

【讨论】:

  • 根据user.id删除posts很容易,因为帖子有一个引用用户的字段,但是如何根据post删除commentscomments 中没有字段可以执行此操作。
猜你喜欢
  • 2017-11-07
  • 2020-02-08
  • 2021-07-15
  • 2014-02-20
  • 2019-01-01
  • 2013-09-30
  • 2020-11-07
  • 2023-03-14
  • 2018-04-03
相关资源
最近更新 更多