在Redux中删除标准化状态中的相关实体的最佳实践

问题描述 投票:2回答:1

从标准化数据中删除实体时,我们如何处理删除被删除实体所拥有的其他实体?例如,对于以下标准化数据,如果我要删除user1,我还想删除user1发布的所有帖子和评论。对于这种情况,有任何已知的方法或最佳实践吗?

{
    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个回答
0
投票

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

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

Option 1

假设您有以下操作:

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

你的user减速器可能如下所示:

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

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

  }

那么在Redux技术上没有任何东西可以阻止你对DELETE_USERposts reducer中的comments动作做出反应:

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

Option 2

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

实施将根据图书馆而有所不同,但其想法是:

  1. DELETE_USER行动
  2. 触发一些操作: 删除用户(DELETE_USER) 删除用户的帖子(DELETE_USER_POSTS) 删除用户的评论(DELETE_USER_COMMENTS
© www.soinside.com 2019 - 2024. All rights reserved.