我正在查看用于构建应用程序状态的记录模式:
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"]
}
Run Code Online (Sandbox Code Playgroud)
我根本不清楚维持allIds该状态的字段有什么好处。以下数据结构不包含完全相同的信息吗?:
posts : {
"post1" : {
id : "post1",
author : "user1",
body : "......",
comments : ["comment1", "comment2"]
},
"post2" : {
id : "post2",
author : "user2",
body : "......",
comments : ["comment3", "comment4", "comment5"]
}
}
Run Code Online (Sandbox Code Playgroud)
在我看来,第一种方法(即官方建议的方法)具有冗余信息,通常被视为缺陷。我看到的第一种方法的唯一好处是我们可以使用该byId属性提前缓存一些帖子。我确信官方 redux 文档有充分的理由建议这种模式。我在一些 React 应用程序中使用了 Redux,但没有太复杂,所以我显然没有看到一些东西。
该allIds领域有几个好处:
Object.keys(state.posts)每次都会创建一个新数组我们的官方 Redux Toolkit 包现在有一个新的createEntityAdapterAPI,它实现了管理这种规范化状态形状的逻辑,它组织为{ids: [], entities: {} }. 它专门实现了保持ids数组按排序顺序排列的功能,并确保ids数组仅在添加、删除项目或排序顺序更改时更改。
您可能还想阅读Advanced Redux Entity Normalization,其中对使用 ID 数组来指示过滤和排序顺序有进一步的思考。
| 归档时间: |
|
| 查看次数: |
2066 次 |
| 最近记录: |