react-router v6嵌套路由简单案例
2022-03-13 本文已影响0人
天渺工作室
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;
image.gif
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;
image.gif
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;
image.gif