使用步骤
- 安装
react-router-dom
依赖
$ npm install react-router-dom@6
- 导入
BrowserRouter, Link, Routes, Route
对象
import {BrowserRouter, Link, Routes, Route} from 'react-router-dom';
3.BrowserRouter:history模式路由; HashRouter:哈希模式路由
示例:
// app.js
import React from "react";
import {BrowserRouter, Link, Routes, Route} from 'react-router-dom';
import Home from './Home';
import About from "./About";function App() {return (<BrowserRouter><Link to="/">首页</Link><Link to="/about">关于</Link><Routes><Route path="/" element={<Home />}></Route><Route path="/About" element={<About />}></Route></Routes></BrowserRouter>)
}export default App;// About.jsfunction About() {return (<div>关于</div>)
}export default About;// Home.jsfunction Home() {return (<div>首页</div>)
}export default Home;
编程式导航
使用 useNavigate
函数实现
// 1.导入 useNavigate 函数
import {useNavigate} from 'react-router-dom';function Home() {const navigate = useNavigate();// 2.跳转到 Login 组件const goLogin = () => {navigate('/Login');}return (<div>首页<button onClick={goLogin}>登录</button></div>)
}export default Home;
路由传参
1. /about?id=100&name=李白
// 传参
navigate('/Login?id=1001&name=李白');// 取参数
import {useSearchParams} from 'react-router-dom';const [params] = useSearchParams();
const id = params.get("id");
const name = params.get("name");
2./about/1000
// 传参
navigate('/Login/1000');// 取参数
import {useParams} from 'react-router-dom';const params = useParams();
const id = params.id
嵌套路由
Outlet
声明嵌套路由出口
如下 Layout
下边包含两个 二级路由 User
和 Info
其中,通过增加 index
属性 来设置默认项
// Layout.jsx
import { Outlet } from "react-router-dom";export default function Layout() {return (<div>Layout{/* 二级路由出口 */}<Outlet></Outlet></div>)
}// App.js
function App() {return (<BrowserRouter><Link to="/">首页</Link><Link to="/about">关于</Link><Routes><Route path="/" element={<Home />}></Route><Route path="/About" element={<About />}></Route><Route path="/Login" element={<Login/>}></Route><Route path="/Layout" element={<Layout/>}>{/** index 设置该路由为默认项 */}<Route index element={<Info/>}></Route><Route path="User" element={<User/>}></Route></Route></Routes></BrowserRouter>)
}
404匹配
function App() {return (<BrowserRouter><Link to="/">首页</Link><Link to="/about">关于</Link><Routes><Route path="/" element={<Home />}></Route><Route path="/About" element={<About />}></Route>]{/** 所有路由都未匹配上 404兜底 */}<Route path="*" element={<NotFound />}></Route></Routes></BrowserRouter>)
}
路由懒加载
需要借助 lazy
、 Suspense
import {lazy, Suspense} from "react";
import {createBrowserHistory} from "history";
import {HistoryRouter} from "react-router-dom";// 按需导入组件
const Login = lazy(() => import("./pages/Login"));let history = createBrowserHistory();// 使用 Suspense 包裹着组件, fallback中设置的是 loadig样式
function App() {return (<HistoryRouter histtory={history}><Suspensefallback={<divstyle={{textAlign: 'center',marginTop: 200}}>Loading....</div>}><Routes>....</Routes></Suspense></HistoryRouter>)
}