React Routes
Let's not rush, let's first review the basic process of setting up React routes. Since React route management is not unified, here we use route management based on useRoutes.
1. Install
npm install react-router-dom@6 Copy code
2. Mount in index.js
import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; import { BrowserRouter,HashRouter } from "react-router-dom"; const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<BrowserRouter> <App /> </BrowserRouter>);
3. Define the route array
/router/index.js
import Page1 from "./../views/Page1";
import Page2 from "./../views/Page2";
import Login from "./../views/Login";
import NotFound from "./../views/404";
export default [
{
path:'/',
element:<Page1/>,
auth:false
},
{
path:'/page2',
element:<Page2/>,
auth:true
},
{
path:'/login',
element:<Login/>
},
{
path:'/404',
element:<NotFound/>
}
]
import Page1 from "./../views/Page1"; import Page2 from "./../views/Page2"; import Login from "./../views/Login"; import NotFound from "./../views/404"; export default [
{ path:'/', element:<Page1/>, auth:false },
{ path:'/page2', element:<Page2/>, auth:true },
{ path:'/login', element:<Login/> },
{ path:'/404', element:<NotFound/> }
] Copy code
4. Use useRoutes in App.js to manage routes
import {useRoutes} from "react-router-dom"
import router from "./router/index";
function App() {
return useRoutes(router);
}
export default App;
<p>
After the above four steps, a simple React route is set up successfully, and you can easily switch between route pages.
</p>
<h2 data-id="heading-2">
Route Guard
</h2>
<p>
Finally, it's time to get started. Fasten your seat belts. After the brief introduction above, we know how to build a simple route management. So how to implement route guards based on the above knowledge? Well, without further ado, please continue reading.
</p>
<h3 data-id="heading-3">
1. Keep the route array unchanged, same as /router/index.js above
</h3>
<h3 data-id="heading-4">
2. Create a function route component to simulate route guard /router/beforeEnter.js
</h3>
import {useLocation,useNavigate,useRoutes} from "react-router-dom";
import {useState,useEffect} from "react";
const BeforeEnter = ({routers}) => {
//1. Find the route item corresponding to the current page path in the route array
const fineRouter = (routes,path) => {
for(let val of routers) {
if(val.path===path) return val;
if(val.children) return fineRouter(val.children,path);
}
return null;
}
//2. Route guard judgment
const judgeRouter = (location,navigate) => {
const {pathname} = location;
//2.1 Find the route item in the route array
const findRoute = fineRouter(routers,pathname);
//2.2 If not found, it means the route does not exist, directly 404
if(!findRoute) {
navigate("/404");
return ;
}
//2.3 If the route item has permission requirements, perform logic verification
if(findRoute.auth) {
// User not logged in, redirect to login page
if(!localStorage.getItem("user")) navigate("/login");
}
}
//3. Listen to route changes via useEffect. Then the component reloads and re-verifies permissions.
const navigate = useNavigate();
const location = useLocation();
const router = useRoutes(routers);
useEffect(()=>{
// Route guard judgment
judgeRouter(location,navigate)
},[navigate,location])
return router;
}
export default BeforeEnter;
3. App.js
App.js only needs a few simple lines of code.
import {useRoutes} from "react-router-dom"
import BeforeEnter from "./router/beforeEnter";
import router from "./router/index";
function App() {
return <BeforeEnter routers={router}/>
}
export default App;
</pre>
4. Demo
To enhance the effect, let's explain based on the above route components. I will list the functions of each route page one by one. In the route array, we agree that if a route item has auth:true, it means the route requires permission verification. Here we check whether the user is logged in.
Page1.js
According to the route array, we know that this component is the home page and does not require permission verification.
export default () => { return <div>Home</div> } Copy code
<p>
<strong>Page2.js</strong>
</p>
<p>
According to the route array, we know that this component requires permission verification.
</p>
export default () => { return <div>page2</div> } Copy code
<p>
<strong>404.js</strong>
</p>
<p>
According to the route array, this component is used when the route does not match, redirect to the 404 page.
</p>
export default () => { return <div>404</div> } Copy code
<p>
<strong>login.js</strong>
</p>
<p>
According to the route array, this component simulates the login page. If a route requires permission verification and fails, it redirects to the login page. On the login page, we simulate a login effect. After clicking login, it automatically redirects to the home page.
</p>
import {useNavigate} from "react-router-dom"; export default () => { const nav = useNavigate(); return <div> Login page <div onClick={()=>{
localStorage.setItem("user","dzp");
setTimeout(() => {
nav('/');
}, 1000);
}}>
Click to Login </div> </div> } Copy code
<p>
<strong>Complete Demo</strong>
</p>
<p>
<img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/90ec3976dc8345338a0af8075db13602~tplv-k3u1fbpfcp-zoom-in-crop-mark:4536:0:0:0.awebp?" alt="QQ20221215-215427-HD.gif" loading="lazy" class="medium-zoom-image" />
</p>
1. Initially not logged in, we go directly to the home page, works fine 2. We visit page1, works fine 3. We randomly visit page99, automatically redirects to 404 page 4. We visit page2, which requires permission. Since not logged in, automatically redirects to the login page, then we click login to redirect to the home page, then we visit page2 again and find it works successfully.
暂无评论。