react-router-domv6 import Home from '@/pages/home/home';
import UseGuide from "@/pages/useGuide/useGuide";
import { HashRouter, useRoutes, Navigate } from 'react-router-dom';
const Router = () => {
function Routes() {
const routes = useRoutes([
{ path: '/', element: <Navigate to="/home" /> },  //重定向
{ path: '/home', element: <Home /> },
{ path: '/use-guide', element: <UseGuide /> },
]);
return routes;
}
return (
<HashRouter>
<Routes />
</HashRouter>
)
}
export default Router;
不适⽤useRoutes的⽅式创建
import A from '@/pages/a';
import B from '@/pages/b';
import { HashRouter, Routes, Route } from 'react-router-dom';
const Router = () => {
return (
<HashRouter>
<Routes>
<Route exact path="/a" element={<A />} />
<Route path="/b" element={<B />} />
</Routes>
</HashRouter>
)
}
react router v5
export default Router;
然后把项⽬根⽬录下⾯的index.js ⽂件⾥⾯的 App换成以上的组件
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Router from '@/router';
<React.StrictMode>
<Router />
</React.StrictMode>,
)
;
使⽤获取路由参数,如果不知道可以打印⼀下既可以
import { useParams, useSearchParams, useLocation  } from "react-router-dom";
console.log(useSearchParams(),useLocation(),useParams());
v6路由权限控制,第⼀段代码控制,第⼆段代码引⼊使⽤
import React from'react';
import { Navigate } from'react-router-dom';
const PrivateRoute = ({ children }) => {
return false ? (
children
) : (
<Navigate to="/" replace={true} />
);
}
export default PrivateRoute;
import { HashRouter, Routes, Route } from 'react-router-dom'; import PrivateRoute from "./PrivateRoute";
import A from '@/pages/A';
import B from '@/pages/B';
import C from '@/pages/C';
export default function Router() {
return (
<HashRouter>
<Routes>
<Route exact path="/a" element={<A />} />
<Route exact path="/b" element={<B />} />
<Route exact path="/c" element={
<PrivateRoute>  {/**做限制 */}
<C />
</PrivateRoute>
} />
</Routes>
</HashRouter>
)
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。