首页 > 解决方案 > redux 标准化状态:byId 和 allIds 模式

问题描述

我正在通过记录的模式来构建应用程序状态:

https://redux.js.org/recipes/structuring-reducers/normalizing-state-shape

有人看到以下建议的方式来维护假设的博客应用程序的帖子:

 posts : {
    byId : {
        "post1" : {
            id : "post1",
            author : "user1",
            body : "......",
            comments : ["comment1", "comment2"]
        },
        "post2" : {
            id : "post2",
            author : "user2",
            body : "......",
            comments : ["comment3", "comment4", "comment5"]
        }
    },
    allIds : ["post1", "post2"]
}

我完全不清楚将这个allIds领域保持在那个状态有什么好处。以下数据结构是否包含完全相同的信息?:

posts : {
        "post1" : {
            id : "post1",
            author : "user1",
            body : "......",
            comments : ["comment1", "comment2"]
        },
        "post2" : {
            id : "post2",
            author : "user2",
            body : "......",
            comments : ["comment3", "comment4", "comment5"]
        }
}

在我看来,第一种方法(即官方建议的方法)具有冗余信息,通常被视为缺陷。我看到的第一种方法的唯一好处是,如果我们使用该byId属性提前缓存一些帖子。我确信官方的 redux 文档有充分的理由建议这种模式。我在一些 React 应用程序中使用了 Redux,但没有太复杂,所以我肯定看不到某些东西。

标签: reactjsredux

解决方案


allIds领域有几个好处:

  • 它为“所有 ID”提供一致的数组引用,而Object.keys(state.posts)每次都创建一个新数组
  • 它可以作为所有项目的默认排序顺序,无论是基于插入顺序还是其他。

我们的官方 Redux Toolkit 包现在有一个新的createEntityAdapterAPI,它实现了管理这种标准化状态形状的逻辑,它组织为{ids: [], entities: {} }. 它专门实现了使ids数组保持排序顺序的能力,并确保ids数组仅在添加、删除项目或排序顺序更改时才更改。

您可能还想通读Advanced Redux Entity Normalization,它对使用 ID 数组来指示过滤和排序顺序有进一步的想法。


推荐阅读