javascript - 在 React UI 中使用规范化的 Redux 状态之前,是否应该对其进行非规范化?
问题描述
我最近开始使用 Normalizr 库来对 Redux 状态的 API 响应进行规范化,但仍有一些部分让我感到困惑。
当使用标准化的 Redux 状态进行 UI 渲染时,将其传递给组件需要额外的 id 道具,而仅定义道具会变得更加复杂
{postIds.map((postId) => (
<Post
postText={entities.posts[postId].body}
commentIds={entities.posts[postId].comments}
postComments={entities.comments}
postAuthor={
entities.users[entities.posts[postId].author.username]
}
/>
))}
你应该在 React UI 中使用数据之前对数据进行非规范化吗?
或者这是一个正常的模式?如果是这样,有什么办法可以简化它?
解决方案
是的,当使用标准化状态时,您通常只会将项目 ID 传递给子组件,并让它使用该 ID 属性查找自己的数据:
const TodoListItem = ({ id }) => {
// Call our `selectTodoById` with the state _and_ the ID value
const todo = useSelector(state => selectTodoById(state, id))
const { text, completed, color } = todo
}
我还建议通读:
- “ Redux Fundamentals”和“Redux Essentials”教程部分关于规范化状态
- Redux Toolkit 使用规范化状态的使用指南。
推荐阅读
- android - 如何为 Android 编写设备驱动程序
- android - 如何仅在登录/登录页面使用 FirebaseAuth 时实现 MVVM?
- java - 在 Listview 上的 2 个 Textview 中显示 2 个数组
- amazon-web-services - CodePipeline 的 Cloudformation 模板
- visual-c++ - VS 2010 C++ 幻象编译错误
- apache - Perl - 使用相对路径 Apache 打开
- c# - 什么是共享令牌缓存凭据身份验证方法?
- javascript - 按特定内容然后按时间戳对 MongoDB 文档进行排序
- ios - WKWebView 是否支持 HTML5 离线应用缓存?
- c# - 从 BluetoothDevice 获取 ClassOfDevice