react-router-dom v6

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>
  )
}

export default Router;

 

然后把项目根目录下面的index.js 文件里面的 App换成以上的组件

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Router from '@/router';

ReactDOM.render(
  <React.StrictMode>
    <Router />
  </React.StrictMode>,
  document.getElementById('root')
);

 

 

使用 获取路由参数,如果不知道可以打印一下既可以

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>
  )
}

 

posted @ 2022-01-12 17:50  狂奔的老鳖  阅读(1207)  评论(0编辑  收藏  举报