我在我的react项目中使用react-redux,显然,有两种方法可以使用redux状态
连接
或useSelector
,
我的 redux 存储每个页面都有一个 reducer ,
对于主页 > homePageReducer
对于消息页面> messagePageReducer
用于身份验证> authReducer
对于用户的博客> blogReducer
对于设置> userSettingsReducer
对于用户个人资料> userProfileReducer
在我的顶级组件或主组件中,我使用了选择器 Hook 来获取所有 reducer 并将 reducer 作为 Prop 传递给所需的组件
const {home, messages, auth, settings, blogs} = useSelector( (state:RootState) => state)
return(
<main>
<Switch>
<Route exact to={HOME_ROUTE}>
<HomeApp auth={auth} settings={settings} userProfile={userProfile}/>
</Route>
<Route exact to={CHAT_ROUTE}>
<ChatApp auth={auth} messages={messages} userProfile={userProfile}/>
</Route>
<Route exact to={BLOG_ROUTE}>
<BlogApp auth={auth} blogs={blogs} userProfile={userProfile}/>
</Route>
</Switch>
</main>
)
这对我的项目来说是一个很好的架构,并且不会给我的项目带来性能问题,还是我应该在这些组件中使用 connect
或 useSelector hook
?
什么更好?
最佳答案
Redux 有一个非常有用的 Style Guide解释所有当前的最佳实践。该列表中有一些适用于您的示例的建议。
Use the React-Redux Hooks API
Prefer using the React-Redux hooks API (
useSelector
anduseDispatch
) as the default way to interact with a Redux store from your React components.
Connect More Components to Read Data from the Store
Prefer having more UI components subscribed to the Redux store and reading data at a more granular level. This typically leads to better UI performance, as fewer components will need to render when a given piece of state changes.
Call useSelector Multiple Times in Function Components
When retrieving data using the
useSelector
hook, prefer callinguseSelector
many times and retrieving smaller amounts of data, instead of having a single largeruseSelector
call that returns multiple results in an object.
您肯定想使用useSelector
。您的 Route
渲染组件不应该选择任何 props,而是从 Redux 本身获取所需的一切,而不是选择父级中的所有内容并将其传递下去。
const App = {
return(
<Switch>
<Route exact to={HOME_ROUTE}>
<HomeApp />
</Route>
<Route exact to={CHAT_ROUTE}>
<ChatApp />
</Route>
<Route exact to={BLOG_ROUTE}>
<BlogApp />
</Route>
</Switch>
)
}
const HomeApp = () => {
const userProfile = useSelector( (state: RootState) => state.user );
// We probably don't need the whole auth object
const isLoggedIn = useSelector( (state: RootState) => !! state.auth );
// Do you need to return *every* setting? Just select what you need.
const settings = useSelector( (state: RootState) => state.settings );
...
}
您可能想要create selector functions特别是对于像 userProfile
这样经常访问的值。
修改当前组件 HomeApp
等的另一种方法是创建一个 HomeScreen
组件作为 HomeApp
的包装器并保留 HomeApp
作为纯粹的演示组件。 HomeScreen
将从 Redux 获取所有数据,并使用正确的 props 调用 HomeApp
。
关于javascript - 我应该使用 connect 还是 hooks 来进行 React Redux,哪个性能更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66527982/