How to jump between multiple pages in react

藏色散人
Release: 2023-01-05 09:48:18
Original
2399 people have browsed it

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.

How to jump between multiple pages in react

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
Copy after login

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

  • ##Administrator

    : Can access the management page/admin and all other pages

  • ##Introducing React-Router

To implement routing authentication, we have to do it step by step , we first use React-Router to build a simple project with these pages. We directly use create-react-app

to create a new project, and then create a

pages folder and put the pages we mentioned earlier in it:

Let’s make our page simpler first. Let’s write a title first, like this: How to jump between multiple pages in react
import React from 'react';

function Admin() {
  return (
    <h1>管理员页面</h1>
  );
}
Copy after login

The other pages are similar.
Then we can introduce

React-Router

in

App.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

: Core logic processing, providing some public base classes

react-router-dom

: Specific implementation of browser-related Route monitoring and jumping

react-router-native

: Specific implementation of RN-related routing monitoring and jumping

In actual use, we generally do not need to quotereact-router

, but just use

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 &amp;#39;react&amp;#39;; import { BrowserRouter as Router, Switch, Route, } from &quot;react-router-dom&quot;; import Home from &amp;#39;./pages/Home&amp;#39;; import Login from &amp;#39;./pages/Login&amp;#39;; import Backend from &amp;#39;./pages/Backend&amp;#39;; import Admin from &amp;#39;./pages/Admin&amp;#39;; function App() { return ( &lt;Router&gt; &lt;Switch&gt; &lt;Route path=&quot;/login&quot; component={Login}/&gt; &lt;Route path=&quot;/backend&quot; component={Backend}/&gt; &lt;Route path=&quot;/admin&quot; component={Admin}/&gt; &lt;Route path=&quot;/&quot; component={Home}/&gt; &lt;/Switch&gt; &lt;/Router&gt; ); } export default App;</pre><div class="contentsignin">Copy after login</div></div>

Then you can use
Link
on the

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 &amp;#39;react&amp;#39;; import { Link } from &amp;#39;react-router-dom&amp;#39;; function Home() { return ( &lt;&gt; &lt;h1&gt;首页&lt;/h1&gt; &lt;ul&gt; &lt;li&gt;&lt;Link to=&quot;/login&quot;&gt;登录&lt;/Link&gt;&lt;/li&gt; &lt;li&gt;&lt;Link to=&quot;/backend&quot;&gt;后台&lt;/Link&gt;&lt;/li&gt; &lt;li&gt;&lt;Link to=&quot;/admin&quot;&gt;管理员&lt;/Link&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/&gt; ); } export default Home;</pre><div class="contentsignin">Copy after login</div></div>

Now our application runs like this:

模块划分

虽然我们的跳转实现了,但是所有人都可以访问任何页面,我们前面的需求是要根据登录的角色限制访问的页面的,在写代码前,我们先来思考下应该怎么做这个。当然最直观最简单的方法就是每个页面都检测下当前用户的角色,匹配不上就报错或者跳回首页。我们现在只有几个页面,这样做好像也还好,但是如果我们的应用变大了,页面变多了,每个页面都来一次检测就显得很重复了,所以我们应该换个角度来思考这个问题。

仔细一看,其实我们总共就三种角色,对应三种不同的权限,这三个权限还有层级关系,高级别的权限包含了低级别的权限,所以我们的页面也可以按照这些权限分为三种:

公共页面
普通页面
管理员页面
Copy after login

为了好管理这三种页面,我们可以将他们抽取成三个文件,放到一个独立的文件夹 routes 里面,三个文件分别命名为 publicRoutes.jsprivateRoutes.jsadminRoutes.js

How to jump between multiple pages in react

对于每个路由文件,我们可以将这类路由组织成数组,然后 export 出去给外面调用,比如 publicRoutes.js

import Login from &#39;../pages&#39;;
import Home from &#39;../pages/Home&#39;;

const publicRoutes = [
  {
    path: &#39;/login&#39;,
    component: Login,
    exact: true,
  },
  {
    path: &#39;/&#39;,
    component: Home,
    exact: true,
  },
];

export default publicRoutes;
Copy after login

然后我们外面使用的地方直接改为:

import publicRoutes from &#39;./routes/publicRoutes&#39;;

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>
  );
}
Copy after login

这样我们的 App.js 里面就不会有冗长的路由路由列表了,而是只需要循环一个数组就行了。但是对于需要登录才能访问的页面和管理员页面我们不能直接渲染 Route 组件,我们最好再封装一个高级组件,将鉴权的工作放到这个组件里面去,这样我们普通的页面在实现时就不需要关心怎么鉴权了。

封装高级组件

要封装这个鉴权组件思路也很简单,前面我们将 publicRoutes 直接拿来循环渲染了 Route 组件,我们的鉴权组件只需要在这个基础上再加一个逻辑就行了:在渲染真正的 Route 组件前先检查一下当前用户是否有对应的权限,如果有就直接渲染 Route 组件,如果没有就返回某个页面,可以是登录页或者后台首页,具体根据自己项目需求来。所以我们的路由配置文件 privateRoutes.jsadminRoutes.js 里面的路由会比 publicRoutes.js 的多两个参数:

// privateRoutes.js
import Backend from &#39;../pages/Backend&#39;;

const privateRoutes = [
  {
    path: &#39;/backend&#39;,
    component: Backend,
    exact: true,
    role: &#39;user&#39;,       // 当前路由需要的角色权限
    backUrl: &#39;/login&#39;   // 不满足权限跳转的路由
  },
];

export default privateRoutes;
Copy after login

adminRoutes.js 是类似的写法:

// adminRoutes.js
import Admin from &#39;../pages/Admin&#39;;

const adminRoutes = [
  {
    path: &#39;/admin&#39;,
    component: Admin,
    exact: true,
    role: &#39;admin&#39;,       // 需要的权限是admin
    backUrl: &#39;/backend&#39;  // 不满足权限跳回后台页面
  },
];

export default adminRoutes;
Copy after login

然后就可以写我们的高级组件了,我们将它命名为 AuthRoute 吧,注意我们这里假设的用户登录时后端API会返回给我们当前用户的角色,一个用户可能有多个角色,比如普通用户的角色是 [&#39;user&#39;] ,管理员的角色是 [&#39;user&#39;, &#39;admin&#39;] ,具体的权限验证逻辑要看自己项目权限的设计,这里只是一个例子:

// AuthRoute.js
import React from &#39;react&#39;;
import { Route, Redirect } from &#39;react-router-dom&#39;;

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;
Copy after login

然后用我们的 AuthRoute 的渲染 adminRoutesprivateRoutes :

// ... 省略其他代码 ...

{privateRoutes.map(
  (route) => <AuthRoute key={route.path} {...route}/>
)}
{adminRoutes.map(
  (route) => <AuthRoute key={route.path} {...route}/>
)}
Copy after login

登录设置权限

在我们的 AuthRoute 里面用到了 user: { role } 这个变量,但是我们还没设置它。真实项目中一般是登录的时候后端API会返回当前用户的角色,然后前端将这个权限信息保存在一些状态管理工具里面,比如 Redux 。我们这里直接在 Login 页面写死两个按钮来模拟这个权限了,用户的配置就用根组件的 state 来管理了, Login 页面的两个按钮会改变对应的 state

import React from &#39;react&#39;;
import { Link } from &#39;react-router-dom&#39;;

function Login(props) {
  const {loginAsUser, loginAsAdmin, history} = props;

  const userLoginHandler = () => {
    loginAsUser();      // 调用父级方法设置用户权限
    history.replace(&#39;/backend&#39;);     // 登录后跳转后台页面
  }

  const adminLoginHandler = () => {
    loginAsAdmin();     // 调用父级方法设置管理员权限
    history.replace(&#39;/admin&#39;);     // 登录后跳转管理员页面
  }

  return (
    <>
      <h1>登录页</h1>
      <button onClick={userLoginHandler}>普通用户登录</button>
      <br/><br/>
      <button onClick={adminLoginHandler}>管理员登录</button>
      <br/><br/>
      <Link to="/">回首页</Link>
    </>
  );
}

export default Login;
Copy after login

到这里我们这个简单的路由鉴权就完成了,具体跑起来效果如下:

How to jump between multiple pages in react

Summary

  • ##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 packagesreact- 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.

  • For routes that require different permissions, we can separate them into categories and build them into a separate file. If there are not many routes, we can put them in one file and export multiple arrays.

  • For routes that require authentication, we can use an advanced component to encapsulate the logic of permission verification. Other pages only need to be configured, and there is no need to worry about authentication issues at all. .

The content of this article is relatively simple. It is not bad as a familiar usage of

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!

Recommended learning: "

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template