gpt4 book ai didi

javascript - ReactJS 使用 Hooks 和 Redux 的良好实践。我应该在每个组件中使用 useSelector,还是应该通过 props 传递?

转载 作者:行者123 更新时间:2023-12-01 16:25:52 26 4
gpt4 key购买 nike

我应该在每个子组件中使用相同的 useSelector 还是应该通过 props 传递 useSelector?

下面的两个例子都有效,我只想知道什么是最佳实践。

通过 props 传递的示例:

const FatherComponent = () => {
const userId = useSelector((state) => state.user.id);

return (
<ChildComponent userId={userId} />
)
}

const ChildComponent = ({userId}) => {
return (
<>{userId}</>
)
}

或重复使用选择器的示例:
const FatherComponent = () => {
const userId = useSelector((state) => state.user.id);

return (
<ChildComponent />
)
}

const ChildComponent = () => {
const userId = useSelector((state) => state.user.id);

return (
<>{userId}</>
)
}

最佳答案

更喜欢让更多 UI 组件订阅 Redux 存储并以更精细的级别读取数据
为了完整起见,以上是来自官方 redux 网站的推荐。
完全归功于指向评论部分页面的尼古拉斯塔。

Prefer having more UI components subscribed to the Redux store andreading data at a more granular level. This typically leads to betterUI performance, as fewer components will need to render when a givenpiece of state changes.

For example, rather than just connecting a component andreading the entire array of users, have retrieve a list ofall user IDs, render list items as , andhave be connected and extract its own user entry fromthe store.

This applies for both the React-Redux connect() API and theuseSelector() hook.


从链接 - https://redux.js.org/style-guide/style-guide#connect-more-components-to-read-data-from-the-store

关于javascript - ReactJS 使用 Hooks 和 Redux 的良好实践。我应该在每个组件中使用 useSelector,还是应该通过 props 传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61661619/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com