问题描述
我最近开始使用 normalizr 库来规范 Redux 状态的 API 响应,但仍有一些部分让我感到困惑。
当使用归一化的 Redux 状态进行 UI 渲染时,将其传递给组件需要额外的 id props,而仅仅定义 props 会变得更加复杂
{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 中使用数据之前,您是否应该对其进行非规范化处理?
或者这是一个正常的模式?如果是这样,有什么方法可以简化吗?
解决方法
是的,当使用归一化状态时,您通常会only pass an item ID to the child component,and let it look up its own data using that ID prop:
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
}
我还建议通读一遍: