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("/");
}}></div>
</div>
);
};
export default Child;
