search
HomeWeb Front-endFront-end Q&AHow to jump between multiple pages in react

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

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 id="管理员页面">管理员页面</h1>
  );
}

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

Then you can use
Link
on the

Home page to add links to jump to other pages, so you can jump:<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 id=&quot;首页&quot;&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>

Now our application runs like this:

模块划分

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

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

公共页面
普通页面
管理员页面

为了好管理这三种页面,我们可以将他们抽取成三个文件,放到一个独立的文件夹 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;

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

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

这样我们的 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;

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;

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

// 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;

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

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

{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 &#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 id="登录页">登录页</h1>
      <button onClick={userLoginHandler}>普通用户登录</button>
      <br/><br/>
      <button onClick={adminLoginHandler}>管理员登录</button>
      <br/><br/>
      <Link to="/">回首页</Link>
    </>
  );
}

export default 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!

Statement
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
React: The Foundation for Modern Frontend DevelopmentReact: The Foundation for Modern Frontend DevelopmentApr 19, 2025 am 12:23 AM

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

The Future of React: Trends and Innovations in Web DevelopmentThe Future of React: Trends and Innovations in Web DevelopmentApr 19, 2025 am 12:22 AM

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

React: A Powerful Tool for Building UI ComponentsReact: A Powerful Tool for Building UI ComponentsApr 19, 2025 am 12:22 AM

React is a JavaScript library for building user interfaces. Its core idea is to build UI through componentization. 1. Components are the basic unit of React, encapsulating UI logic and styles. 2. Virtual DOM and state management are the key to component work, and state is updated through setState. 3. The life cycle includes three stages: mount, update and uninstall. The performance can be optimized using reasonably. 4. Use useState and ContextAPI to manage state, improve component reusability and global state management. 5. Common errors include improper status updates and performance issues, which can be debugged through ReactDevTools. 6. Performance optimization suggestions include using memo, avoiding unnecessary re-rendering, and using us

Using React with HTML: Rendering Components and DataUsing React with HTML: Rendering Components and DataApr 19, 2025 am 12:19 AM

Using HTML to render components and data in React can be achieved through the following steps: Using JSX syntax: React uses JSX syntax to embed HTML structures into JavaScript code, and operates the DOM after compilation. Components are combined with HTML: React components pass data through props and dynamically generate HTML content, such as. Data flow management: React's data flow is one-way, passed from the parent component to the child component, ensuring that the data flow is controllable, such as App components passing name to Greeting. Basic usage example: Use map function to render a list, you need to add a key attribute, such as rendering a fruit list. Advanced usage example: Use the useState hook to manage state and implement dynamics

React's Purpose: Building Single-Page Applications (SPAs)React's Purpose: Building Single-Page Applications (SPAs)Apr 19, 2025 am 12:06 AM

React is the preferred tool for building single-page applications (SPAs) because it provides efficient and flexible ways to build user interfaces. 1) Component development: Split complex UI into independent and reusable parts to improve maintainability and reusability. 2) Virtual DOM: Optimize rendering performance by comparing the differences between virtual DOM and actual DOM. 3) State management: manage data flow through state and attributes to ensure data consistency and predictability.

React: The Power of a JavaScript Library for Web DevelopmentReact: The Power of a JavaScript Library for Web DevelopmentApr 18, 2025 am 12:25 AM

React is a JavaScript library developed by Meta for building user interfaces, with its core being component development and virtual DOM technology. 1. Component and state management: React manages state through components (functions or classes) and Hooks (such as useState), improving code reusability and maintenance. 2. Virtual DOM and performance optimization: Through virtual DOM, React efficiently updates the real DOM to improve performance. 3. Life cycle and Hooks: Hooks (such as useEffect) allow function components to manage life cycles and perform side-effect operations. 4. Usage example: From basic HelloWorld components to advanced global state management (useContext and

React's Ecosystem: Libraries, Tools, and Best PracticesReact's Ecosystem: Libraries, Tools, and Best PracticesApr 18, 2025 am 12:23 AM

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

React and Frontend Development: A Comprehensive OverviewReact and Frontend Development: A Comprehensive OverviewApr 18, 2025 am 12:23 AM

React is a JavaScript library developed by Facebook for building user interfaces. 1. It adopts componentized and virtual DOM technology to improve the efficiency and performance of UI development. 2. The core concepts of React include componentization, state management (such as useState and useEffect) and the working principle of virtual DOM. 3. In practical applications, React supports from basic component rendering to advanced asynchronous data processing. 4. Common errors such as forgetting to add key attributes or incorrect status updates can be debugged through ReactDevTools and logs. 5. Performance optimization and best practices include using React.memo, code segmentation and keeping code readable and maintaining dependability

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools