首页 > 解决方案 > 在 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 中使用数据之前对数据进行非规范化吗?
或者这是一个正常的模式?如果是这样,有什么办法可以简化它?

标签: javascriptjsonreactjsreduxnormalizr

解决方案


是的,当使用标准化状态时,您通常只会将项目 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

}

我还建议通读:


推荐阅读