1. 程式人生 > 其它 >react-router v6 巢狀路由中子路由頁面不渲染問題

react-router v6 巢狀路由中子路由頁面不渲染問題

BasicLayout是我的父元件,menu.js 配置了所有的子元件路由

如下

父元件路由配置

 1 export default [
 2     {
 3         path: '/nomatch/:type',
 4         component: NoMatch,
 5     },
 6     {
 7         path: '',
 8         component: BasicLayout,
 9         render: () => <Navigate to="/" />,
10     },
11     {
12         path: '/',
13 component: BasicLayout, 14 // exact: false, 15 }, 16 ];

子元件路由配置

 1 export default [
 2     {
 3         path: '/home',
 4         meta: {
 5             title: '首頁',
 6             icon: <SettingOutlined />,
 7         },
 8         name: 'Home',
 9         component: React.lazy(() => import('../pages/Home')),
10 // component: Home 11 }, 12 { 13 path: '/about', 14 meta: { 15 title: '關於', 16 icon: <SettingOutlined />, 17 }, 18 name: 'Home', 19 redirect: '/me', 20 routes:[ 21 { 22 path: '/me', 23
meta: { 24 title: '個人資訊', 25 icon: <SettingOutlined />, 26 }, 27 name: 'Me', 28 component: React.lazy(() => import('../pages/About')), 29 } 30 ], 31 }, 32 ];

父元件跳轉配置

<Content style={{ margin: ' 16px' }}>
                        <div className="site-layout-background" style={{ padding: 24, minHeight: 360 }}>
                            <p>主頁面</p>
                            {createRoutes(combineRoutePermissions(pageRoutes, authorityKeys), { authorityKeys })}
                            <Link to='home'>home </Link>
                            <Link to='about/me'>關於</Link>
                        </div>
                    </Content>

點選home會跳轉空白

檢視warning資訊

您在“/”(在<Route path=“”>)下)呈現了子體<Routes>(或呼叫了`useRoutes()`),但父路由路徑沒有尾隨“*”。這意味著,如果導航得更深,父路由將不再匹配,因此子路由將永遠不會渲染。

修改:給父元件路徑新增 *

export default [
    {
        path: '/nomatch/:type',
        component: NoMatch,
    },
    {
        path: '',
        component: BasicLayout,
        render: () => <Navigate to="/*" />,
    },
    {
        path: '/*',
        component: BasicLayout,
        // exact: false,
    },
];

這樣就好了。

不積跬步無以至千里