我在我的react项目中使用redux -redux,很明显,有两种方法可以使用redux状态connect或useSelector,
我的redux商店每页都有一个减速机,
主页> homePageReducer
消息页> messagePageReducer
用于身份验证> authReducer
用于用户博客> blogReducer
用于设置> userSettingsReducer
用于用户配置文件> userProfileReducer
在我的顶层组件或主组件中,我使用了选择器挂钩来获取所有的减速器,并将减速器作为支撑传递给所需的组件。
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?还有什么更好的?
发布于 2021-03-08 20:37:18
Redux有一个非常有用的风格指南,它解释了所有当前的最佳实践。该列表中有一些建议适用于您的示例。
更喜欢使用(
useSelector和useDispatch)作为使用React组件与Redux存储进行交互的默认方式。
更愿意让更多的UI组件订阅Redux存储,并在更细粒度的级别读取数据。这通常会带来更好的UI性能,因为当给定的状态发生变化时,需要呈现的组件较少。
当使用
useSelector钩子检索数据时,更倾向于多次调用useSelector并检索较少的数据,而不是使用一个返回对象中多个结果的更大的useSelector调用。
您肯定想使用useSelector。与其选择父类中的所有内容并将其传递下来,您的Route呈现组件不应该使用任何支持,而应该从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 );
...
}您可能需要创建选择器函数,特别是对于像userProfile这样的常见访问的值。
修改当前组件HomeApp等的一个替代方法是创建一个HomeScreen组件作为HomeApp的包装器,并将HomeApp保持为一个纯表示组件。HomeScreen将从Redux获取所有数据,并使用正确的道具调用HomeApp。
https://stackoverflow.com/questions/66527982
复制相似问题