使用React路由实现模块化

时间:2019-11-11 11:59:32

标签: reactjs react-routing

我是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组件:

enter image description here

看到嵌套路由无法正常工作-应该显示All Resources而不是Resources

enter image description here

我希望可以从const routes导出的对象中读取所有路由并正确路由-包括嵌套页面和/ 404通用页面。

0 个答案:

没有答案