ReactJS中使用react-router-dom配置路由时组件懒加载不生效如何解决?
问题原因与修复方案
1. 父路由配置错误
你在AppViews中匹配${APP_PREFIX_PATH}/commons的路由加了exact属性,当访问/commons/documents时,路径和/commons不是完全匹配,Commons组件直接不会渲染,内部的子路由自然无法生效。
修复:去掉该路由的exact属性
// AppViews 修改后 <Route path={`${APP_PREFIX_PATH}/commons`} component={lazy(() => import(`./commons`))} />
2. 子组件重复声明Router
Commons组件内部额外套了一层<Router>,这会创建独立的路由上下文,和外层Router的状态完全隔离,外层路径变化无法触发内层路由匹配。
修复:删除Commons里多余的<Router>标签
3. Redirect位置错误
路由相关组件必须在Router上下文内才能生效,你把Redirect放在了Switch/ Router外面,不会触发跳转逻辑。另外拼接子路由路径建议用match.path而非match.url,动态路由场景下兼容性更好。
修改后的完整Commons组件代码:
const Commons = ({ match }) => { return ( <Suspense fallback={<Loading cover="content" />}> <Switch> <Route exact path={`${match.path}/documents`} component={lazy(() => import(`./documents`))} /> <Redirect from={`${match.path}`} to={`${match.path}/documents`} /> </Switch> </Suspense> ); }; export default Commons;
修改完成后即可正常渲染Documents组件。
内容的提问来源于stack exchange,提问作者juniorFrontEndDD
相关产品推荐
相关产品推荐

