1. 程式人生 > 其它 >react-router-config 使用

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 Home from '../pages/Home';

import Login
from '../pages/Login';
const routes: any = [
  {
    path: '/',
    exact: true,
    component: Home,
    routes: []
  },
  {
    path: '/home',
    component: Home,
    routes: []
  },
  {
    path: '/login',
    component: Login,
    routes: []
  }
]

export default routes

第四步在 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();

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