我是ReactJS的新手,并且希望在我的代码中实现某种程度的模块化,以便能够轻松地从单个文件/ JSON数组添加/实现新的(嵌套的)路由。
我已经尝试实例化一个包含<Route>
组件期望的强制参数的JSON Array对象,然后将此导出的变量导入App.js
中以对其进行迭代,以便动态生成路由-使用很少的代码行-但是我遇到了很多问题,即嵌套路由和默认的全部捕获行为。
import React, { lazy } from 'react'
import { Redirect } from 'react-router-dom'
const routes = [
{
path: '/about',
component: lazy(() => import(`./about`))
},
--- SNIP ---
{
path: '/resources',
component: lazy(() => import(`./resources`)),
routes: [
{
path: '/resources/all-resources',
component: lazy(() => import(`./resources/all-resources`))
},
{
path: '/resources/blog',
exact: true,
component: lazy(() => import(`./resources/blog`))
},
{
component: () => <Redirect to="/404" />
}
],
},
--- SNIP ---
{
component: lazy(() => import(`./not-found`))
}
]
export default routes;
import React, { Suspense } from 'react';
import { BrowserRouter, Redirect, Route, Switch } from 'react-router-dom';
import { createGlobalStyle, ThemeProvider } from 'styled-components';
import routes from './routes';
--- SNIP ---
function App() {
return (
<ThemeProvider theme={{ mode: 'dark' }}>
<>
<GlobalStyle />
<BrowserRouter>
<Switch>
<Suspense fallback={<div>Loading...</div>}>
{
routes.map((route) =>
<Route path={route.path} component={route.component} exact={route.exact} />
)
}
</Suspense>
</Switch>
</BrowserRouter>
</>
</ThemeProvider>
);
}
export default App;
请参阅以下屏幕快照,显示尽管在有效且预定义的端点中仍显示/ 404组件:
看到嵌套路由无法正常工作-应该显示All Resources
而不是Resources
:
我希望可以从const routes
导出的对象中读取所有路由并正确路由-包括嵌套页面和/ 404通用页面。