react-routerv6嵌套路由简单案例
react-router V6版本路由⽤法和V5⽤法差距较⼤,⼀个简单的使⽤案例
新版本组件也开始使⽤函数式组件+hooks
"react-router-dom": "^6.2.1",
1.⼊⼝
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种
import { useNavigate, Link } from "react-router-dom";react router v5
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("/");
}}></div>
</div>
);
};
export default Child;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论