1. 这里使用react-router-config配置静态路由

npm install react-router-dom--save
npm install react-router-config --save
"react-router-config": "^5.1.1", "react-router-dom": "^5.3.0",

2. 创建src/router/index.js

这里使用react自带的lazy路由懒加载

import {lazy} from "react";
import {Redirect} from "react-router-dom";
const Demo = lazy(() =>import('@/pages/Demo/Index'));
const App = lazy(() =>import('@/pages/Account'));
const notFound = lazy(() => import('@/pages/404'));
const Home = lazy(() => import('@/pages/Home'));
const Page = lazy(() => import('@/pages/Page/Index'));
const Page1 = lazy(() => import('@/pages/Page1/Index'));

const routes = [
    {
        path: '/account',
        exact: true,
        component: App
    },
    {
        path: '/',
        exact: true,
        component: Home
    },
    //嵌套路由
    {
        path: '/home',
        component: Page,
        children: [
            {
                path: '/home',
                exact: true,
                render: () => {
                return <Redirect to={'/home/first'}/>
                }
            },
            { path: "/home/first", component: Demo },
            { path: "/home/second", component: Page1 }
        ]
    },
    // 404
    {
        path: '*',
        component: notFound
    }
]
export default routes;

注意:使用嵌套路由时,compoent和render不能同时存在,如需重定向,嵌套数组的第一个得是他自己。还有一个缺点:访问/home/a会跳到 Page组件,不会跳到 404组件

src/index.js

import { renderRoutes } from "react-router-config";
import routes from "./router";
import {BrowserRouter} from "react-router-dom";
import React, {Suspense} from 'react';

ReactDOM.render(
        <React.StrictMode>
              <BrowserRouter>
                      <Suspense fallback={<div style={{width: '100vw', height: '100vh', background: '#000', padding: 0, margin: 0, color: 'red'}}>loading</div>}> // div是页面的loading
                              {renderRoutes(routes)}
                      </Suspense>
              </BrowserRouter>
        </React.StrictMode>,
  document.getElementById('root')
);

src/pages/Page/Index.js

import React, {Component} from "react";
import {renderRoutes} from "react-router-config";
export default class Page extends Component {
    constructor(props) {
        super(props);
        console.log(props);
        this.state = {
            route: props.route
        }
    }
    render () {
        return <div>
            <div>菜单</div>
            {renderRoutes(this.state.route.children) } // 这里对应router/index.js里的children数组,在父组件内要加上这一句
          </div>
    }
}

使用路由懒加载要配上Suspense组件,用于在等待某个异步组件解析时显示后备内容。fallback 属性接受任何在组件加载过程中你想展示的 React 元素。你可以将 Suspense 组件置于懒加载组件之上的任何位置。你甚至可以用一个 Suspense 组件包裹多个懒加载组件。

 posted on 2021-09-28 14:16  Yseraaa  阅读(681)  评论(0编辑  收藏  举报