【问题标题】:redux normalized state: byId and allIds patternredux 标准化状态:byId 和 allIds 模式
【发布时间】:2020-05-23 00:18:03
【问题描述】:

我正在查看结构化应用程序状态的文档化模式:

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,但没有太复杂,所以我肯定看不到什么。

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    allIds 字段有几个好处:

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

    Our official Redux Toolkit package 现在有一个新的createEntityAdapter API,它实现了管理这种标准化状态形状的逻辑,它组织为{ids: [], entities: {} }。它专门实现了保持ids 数组按排序顺序的功能,并确保ids 数组仅在添加、删除或更改排序顺序时更改。

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

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 2016-11-22
      • 2017-09-22
      • 2017-09-22
      • 1970-01-01
      • 2019-05-16
      • 2019-02-01
      • 2023-03-23
      相关资源
      最近更新 更多