How to implement jumps between multiple pages in react: 1. Introduce "React-Router"; 2. Use Link on the Home page to add links to jump to other pages; 3. Add multiple routes Just put it in one file and export multiple arrays.
The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.
react How to jump between multiple pages?
react Multi-page jump, use React-Router to implement front-end routing authentication
React-Router
is React It is a very important part of the ecosystem. Nowadays, the routing of React single-page applications is basically managed by the front-end itself, unlike the back-end routing before. The commonly used library for React to manage routing is React-Router
. This article wants to write about the use of React-Router
, but just introducing the API is too plain, and the official documentation is already well written. I will use a common development scenario to take a look here How to use React-Router
. Our general systems have restrictions on user access permissions, and some pages may require users to have certain permissions to access. This article uses React-Router
to implement a front-end authentication model.
Application Example
The function to be implemented in this article is a scenario that everyone often encounters, that is, to control different user roles to access different pages. There are a total of four Pages:
/index /login /backend /admin
There are also three roles:
##Non-logged-in users: Can only access the home page of the website
/index and login page
/login
Ordinary users: can access the website homepage
/index, login page
/login and backend page
/backend
: Can access the management page/admin
and all other pages
pages folder and put the pages we mentioned earlier in it:
import React from 'react'; function Admin() { return ( <h1>管理员页面</h1> ); }
React-Router
inApp.js to do routing jumps. Note that we are using
react on the browser -router-dom, the new version of
React-Router separates the core logic layer and the presentation layer. The core logic will handle route matching, etc., and the presentation layer will handle actual jumps and monitoring of route changes. , the reason why it is so divided is because React-Router not only needs to support browsers, but also needs to support React Native. The monitoring and jumping of these two platforms are different, so now there are several packages under React-Router:
react-router
react-router-dom
react-router-native
In actual use, we generally do not need to quote
react-router
react-router-dom directly, because it will reference
react-router itself. Next we introduce
react-router-dom into the project.
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false;">import React from &#39;react&#39;;
import {
BrowserRouter as Router,
Switch,
Route,
} from "react-router-dom";
import Home from &#39;./pages/Home&#39;;
import Login from &#39;./pages/Login&#39;;
import Backend from &#39;./pages/Backend&#39;;
import Admin from &#39;./pages/Admin&#39;;
function App() {
return (
<Router>
<Switch>
<Route path="/login" component={Login}/>
<Route path="/backend" component={Backend}/>
<Route path="/admin" component={Admin}/>
<Route path="/" component={Home}/>
</Switch>
</Router>
);
}
export default App;</pre><div class="contentsignin">Copy after login</div></div>
Home page to add links to jump to other pages, so you can jump:
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false;">import React from &#39;react&#39;;
import { Link } from &#39;react-router-dom&#39;;
function Home() {
return (
<>
<h1>首页</h1>
<ul>
<li><Link to="/login">登录</Link></li>
<li><Link to="/backend">后台</Link></li>
<li><Link to="/admin">管理员</Link></li>
</ul>
</>
);
}
export default Home;</pre><div class="contentsignin">Copy after login</div></div>
虽然我们的跳转实现了,但是所有人都可以访问任何页面,我们前面的需求是要根据登录的角色限制访问的页面的,在写代码前,我们先来思考下应该怎么做这个。当然最直观最简单的方法就是每个页面都检测下当前用户的角色,匹配不上就报错或者跳回首页。我们现在只有几个页面,这样做好像也还好,但是如果我们的应用变大了,页面变多了,每个页面都来一次检测就显得很重复了,所以我们应该换个角度来思考这个问题。
仔细一看,其实我们总共就三种角色,对应三种不同的权限,这三个权限还有层级关系,高级别的权限包含了低级别的权限,所以我们的页面也可以按照这些权限分为三种:
公共页面 普通页面 管理员页面
为了好管理这三种页面,我们可以将他们抽取成三个文件,放到一个独立的文件夹 routes
里面,三个文件分别命名为 publicRoutes.js
, privateRoutes.js
, adminRoutes.js
:
对于每个路由文件,我们可以将这类路由组织成数组,然后 export
出去给外面调用,比如 publicRoutes.js
:
import Login from '../pages'; import Home from '../pages/Home'; const publicRoutes = [ { path: '/login', component: Login, exact: true, }, { path: '/', component: Home, exact: true, }, ]; export default publicRoutes;
然后我们外面使用的地方直接改为:
import publicRoutes from './routes/publicRoutes'; function App() { return ( <Router> <Switch> {publicRoutes.map( ({path, component, ...routes}) => <Route key={path} path={path} component={component} {...routes}/> )} <Route path="/backend" component={Backend}/> <Route path="/admin" component={Admin}/> </Switch> </Router> ); }
这样我们的 App.js
里面就不会有冗长的路由路由列表了,而是只需要循环一个数组就行了。但是对于需要登录才能访问的页面和管理员页面我们不能直接渲染 Route
组件,我们最好再封装一个高级组件,将鉴权的工作放到这个组件里面去,这样我们普通的页面在实现时就不需要关心怎么鉴权了。
要封装这个鉴权组件思路也很简单,前面我们将 publicRoutes
直接拿来循环渲染了 Route
组件,我们的鉴权组件只需要在这个基础上再加一个逻辑就行了:在渲染真正的 Route
组件前先检查一下当前用户是否有对应的权限,如果有就直接渲染 Route
组件,如果没有就返回某个页面,可以是登录页或者后台首页,具体根据自己项目需求来。所以我们的路由配置文件 privateRoutes.js
, adminRoutes.js
里面的路由会比 publicRoutes.js
的多两个参数:
// privateRoutes.js import Backend from '../pages/Backend'; const privateRoutes = [ { path: '/backend', component: Backend, exact: true, role: 'user', // 当前路由需要的角色权限 backUrl: '/login' // 不满足权限跳转的路由 }, ]; export default privateRoutes;
adminRoutes.js
是类似的写法:
// adminRoutes.js import Admin from '../pages/Admin'; const adminRoutes = [ { path: '/admin', component: Admin, exact: true, role: 'admin', // 需要的权限是admin backUrl: '/backend' // 不满足权限跳回后台页面 }, ]; export default adminRoutes;
然后就可以写我们的高级组件了,我们将它命名为 AuthRoute
吧,注意我们这里假设的用户登录时后端API会返回给我们当前用户的角色,一个用户可能有多个角色,比如普通用户的角色是 ['user']
,管理员的角色是 ['user', 'admin']
,具体的权限验证逻辑要看自己项目权限的设计,这里只是一个例子:
// AuthRoute.js import React from 'react'; import { Route, Redirect } from 'react-router-dom'; function AuthRoute(props) { const { user: { role: userRole }, role: routeRole, backUrl, ...otherProps } = props; // 如果用户有权限,就渲染对应的路由 if (userRole && userRole.indexOf(routeRole) > -1) { return <Route {...otherProps} /> } else { // 如果没有权限,返回配置的默认路由 return <Redirect to={backUrl} /> } } export default AuthRoute;
然后用我们的 AuthRoute
的渲染 adminRoutes
和 privateRoutes
:
// ... 省略其他代码 ... {privateRoutes.map( (route) => <AuthRoute key={route.path} {...route}/> )} {adminRoutes.map( (route) => <AuthRoute key={route.path} {...route}/> )}
在我们的 AuthRoute
里面用到了 user: { role }
这个变量,但是我们还没设置它。真实项目中一般是登录的时候后端API会返回当前用户的角色,然后前端将这个权限信息保存在一些状态管理工具里面,比如 Redux
。我们这里直接在 Login
页面写死两个按钮来模拟这个权限了,用户的配置就用根组件的 state
来管理了, Login
页面的两个按钮会改变对应的 state
:
import React from 'react'; import { Link } from 'react-router-dom'; function Login(props) { const {loginAsUser, loginAsAdmin, history} = props; const userLoginHandler = () => { loginAsUser(); // 调用父级方法设置用户权限 history.replace('/backend'); // 登录后跳转后台页面 } const adminLoginHandler = () => { loginAsAdmin(); // 调用父级方法设置管理员权限 history.replace('/admin'); // 登录后跳转管理员页面 } return ( <> <h1>登录页</h1> <button onClick={userLoginHandler}>普通用户登录</button> <br/><br/> <button onClick={adminLoginHandler}>管理员登录</button> <br/><br/> <Link to="/">回首页</Link> </> ); } export default Login;
到这里我们这个简单的路由鉴权就完成了,具体跑起来效果如下:
##React-Router can be used to manage front-end routing jumps and is the
React ecosystem A very important library inside.
React-Router In order to support both browsers and
React-Native, he split it into three packages
react- router core package,
react-router-dom browser package,
react-router-native supports
React-Native. There is no need to introduce
react-router when using it. You only need to introduce the required platform packages.
React-Router, but we can’t just use it, but also need to know its principles. If you like it, you can like it and follow it!
react video tutorial"
The above is the detailed content of How to jump between multiple pages in react. For more information, please follow other related articles on the PHP Chinese website!