react-router V6版本路由用法和V5用法差距较大,一个简单的使用案例
新版本组件也开始使用函数式组件+hooks
"react-router-dom": "^6.2.1",
1.入口main
import "./App.css";
import { BrowserRouter, Route, Routes, Navigate } from "react-router-dom";
import Index from "./modules/index/Index";
import Error from "./modules/error/Index";
import Admin from "./modules/admin/Index";
const App = () => {
return (
<div className="App">
{/* HashRouter哈希路由 还是 Browser路由随需求选择 */}
<BrowserRouter>
<Routes>
{/* 默认初始化入口/home*/}
<Route path="/" element={<Navigate to="/home" />} />
{/* home模块路由 */}
<Route path="home/*" element={<Index />} />
{/* admin模块路由 */}
<Route path="/admin/*" element={<Admin />} />
{/* 404页面 */}
<Route path="*" element={<Error />} />
</Routes>
</BrowserRouter>
</div>
);
};
export default App;
2.子路由-Index模块(案例举例)
import { Route, Routes } from "react-router-dom";
import MainIndex from "./page/index/Index";
import Nav from "./page/nav/Nav";
import Error from "../error/Index";
const Index = () => {
return (
<div>
<Routes>
{/* path="/"初始化默认 */}
<Route path="/" element={<MainIndex />} />
<Route path="/nav" element={<Nav />} />
{/* 子路由的404页面 */}
<Route path="*" element={<Error />} />
</Routes>
</div>
);
};
export default Index;
3.路由跳转方法2种 useNavigate, Link
import { useNavigate, Link } from "react-router-dom";
const Child = (props) => {
const navigate = useNavigate();
return (
<div>
{/* link跳转 */}
<Link to="/admin/componentDelivery">跳转路由</Link>
<br />
<div onClick={() => {
// 逻辑跳转
navigate("/admin/componentDelivery");
// replace 跳转
// navigate('/home', {replace: true});
// navigate("/");
// 回退步数 0刷新页面
// navigate(-1);
}}></div>
</div>
);
};
export default Child;
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。