reactjs - 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,但没有太复杂,所以我肯定看不到某些东西。
解决方案
该allIds
领域有几个好处:
- 它为“所有 ID”提供一致的数组引用,而
Object.keys(state.posts)
每次都创建一个新数组 - 它可以作为所有项目的默认排序顺序,无论是基于插入顺序还是其他。
我们的官方 Redux Toolkit 包现在有一个新的createEntityAdapter
API,它实现了管理这种标准化状态形状的逻辑,它组织为{ids: [], entities: {} }
. 它专门实现了使ids
数组保持排序顺序的能力,并确保ids
数组仅在添加、删除项目或排序顺序更改时才更改。
您可能还想通读Advanced Redux Entity Normalization,它对使用 ID 数组来指示过滤和排序顺序有进一步的想法。
推荐阅读
- python - 我对这个问题很感兴趣:“DataFrame 的真值是模棱两可的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。”
- excel - 使用 COUNTIF 和基于左侧单元格的文本
- r - 将 GRASS 栅格地图读入 R
- asp.net-web-api - 有时 API 会引发内部服务器错误
- electron - 在现有的基于反应 js 的项目上的电子 js / builder 时出错
- python - Python DataFrame:根据自定义条件分隔行?
- html - 如何允许子元素使用垂直对齐扩展高度:超级
- django - Django - 使用外键查询多个值
- c# - 我可以使用反射设置多个列表项属性值吗?
- django-cms - 更改 Django CMS 中新插件的顺序