react-router-config (嵌套路由)使用

第一步安装 react-router-config (需要注意不支持 react-router-dom 5以上的版本 )

yarn add react-router-config

第二步在 react-app-env.d.ts 中声明引入

/// <reference types="react-scripts" />

declare module 'react-router-config';
declare module 'react-router-dom';

第三步 创建 router 文件 

import SystemFrame from '@/components/SystemFrame';
import Home from '@/pages/Home';
import Login from '@/pages/Login';

const routes: any = [
  {
    path: '/login',
    component: Login,
    routes: []
  },
  {
    path: '/',
    component: SystemFrame,
    // exact: true,
    routes: [
      {
        path: '/home',
        component: Home,
        routes: []
      }
    ]
  }
]

export default routes

SystemFrame 组件

import { renderRoutes } from "react-router-config";
import React from "react";
import HeaderComps from "@/components/Header"
import MenuComps from "@/components/Menu"
import { SystemFrameWrapper } from './styled'

const SystemFrame: React.FC = (props: any) => {
  return (
    <SystemFrameWrapper className="system-frame-wrapper">
      <div className="system-frame-main">
        <div className="system-frame-main-left">
          <MenuComps></MenuComps>
        </div>
        <div className="system-frame-main-right">
          <HeaderComps></HeaderComps>
          { renderRoutes(props.route.routes) }
        </div>
      </div>
    </SystemFrameWrapper>
  )
}

export default SystemFrame

需注意在使用嵌套路由的时候,当 父级路由的 path 为 "/" 的时候,不能开启 exact 模式,而且该路由必须放在最后面,否则会导致匹配不上路由,从而导致页面空白;而且当一个组件作为父级路由使用时,必须再次执行 renderRoutes 方法,如 SystemFrame 组件

第四步在 App.tsx 中引入使用

import { BrowserRouter } from 'react-router-dom';
import { renderRoutes } from "react-router-config";
import routes from "./router";
function App() {
  return (
    <BrowserRouter>
      { renderRoutes(routes) }
    </BrowserRouter>
  );
}
export default App;

第五步在 index.tsx 中展示 App 组件

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
// 性能检测工具
import reportWebVitals from './reportWebVitals';


ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

完成以上步骤就能在浏览器上自由切换了

 

posted @ 2022-03-10 18:14  爱放屁的菜鸟  阅读(1743)  评论(0编辑  收藏  举报