如何为同一组件配置多路径路由?多路径配置后页面空白问题排查
问题解决:多路径路由配置后根路径页面空白
React Router v6及以上版本不支持将path属性设置为数组形式,你当前的写法会导致根路径/无法正确匹配子路由的index元素,因此页面显示空白,只有/home路径能正常工作。
修正后的路由配置
你需要将原路由拆分为两个独立的路由项,复用相同的布局组件和子路由:
// 先抽离共享的子路由,避免代码重复 const layoutChildren = [ { index: true, element: <Home />, }, { path: "profile", element: <Profile />, auth: "user", }, ]; const routes = [ { path: "/", element: <GeneralLayout />, children: layoutChildren, }, { path: "/home", element: <GeneralLayout />, children: layoutChildren, }, ];
原理说明
拆分后,/和/home会分别匹配对应的路由项,都能正确加载GeneralLayout组件,并渲染子路由中的index元素(Home组件)。访问/profile或/home/profile时,也会正常加载对应的Profile组件。
内容的提问来源于stack exchange,提问作者Nabil yahya
相关产品推荐
相关产品推荐

