安装
npm install react-router-dom
main.tsx中配置
import React from 'react'
import { RouterProvider } from 'react-router-dom'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import 'normalize.css'
import './index.css'import router from './router/index.ts'ReactDOM.createRoot(document.getElementById('root')!).render(<React.StrictMode><RouterProvider router={ router } ><App /></RouterProvider></React.StrictMode>,
)
router文件夹下index.ts路由表配置
import { createBrowserRouter } from "react-router-dom";
import Layout from "@/pages/layout/Layout";
import Login from "@/pages/login/Login";
import Home from "@/pages/home/Home";import type { Routes } from '@/types/router'const routes:Array<Routes> = [{path:'/',//注意:这里C要大写Component:Layout,children:[//react-router路由表配置没有redirect重定向,故此在这里多加一项Home配置,同样能达 //到重定向效果{path:'/',Component:Home},{path:'/home',Component:Home}]},{path:'/login',Component:Login}
]const router = createBrowserRouter(routes)export default router
App组件中使用
import { Outlet } from 'react-router-dom'
import "./App.less";function App() {return (<div className="app"> <Outlet /></div>);
}export default App;
获取路由路径 useLocation
编程式导航 useNavigate
获取路由参数 useParams