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();

完成以上步驟就能在瀏覽器上自由切換了

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM