Table of Contents
Routing Background-SPA
Routing reference and usage
Routing components and attributes
Link
IndexRoute
AppComponent.js
LoginComponent.js
HomeComponent.js
Router.js
模块化
router.js
编程式导航
路由钩子函数
onEnter
onLeave
Home Web Front-end JS Tutorial Detailed explanation of routing in React

Detailed explanation of routing in React

May 24, 2018 pm 02:20 PM
react Detailed explanation routing

This time I will bring you a detailed explanation of the use of routing in React. What are the precautions for using routing in React? The following is a practical case, let's take a look.

Routing

is implemented by mapping the URL to the corresponding function. To use React routing, react-router.js must be introduced first.
Note:
There is a big difference between version 4.0 and above of react-router and version 3.0 and below. This tutorial uses version 3.0.2, and tutorials for versions 4.0 and above will be updated later.
When installing using npm, the latest version is installed by default. If the installed version is the latest and the 3.0 version is used, an error will be reported.
So you need to specify the version when installing npm npm install react-router@3.0.2 --save-dev.

Routing Background-SPA

The traditional front-end basically switches between functional modules by jumping between pages. This approach will lead to a large number of html pages in a project. Moreover, each page has a lot of static resource files that need to be imported, which has always been a problem in terms of performance. Later, with the popularity of ajax and the convenient use of jQuery's encapsulation of ajax, developers will use ajax extensively to load an html page into a container of the current page to achieve non-refresh loading, but there is still no Solve the performance problems caused by the presence of a large number of html pages and the loading of a large number of static resource files on each page. With the popularity of mobile Internet, mobile terminals have increasingly higher performance requirements and traffic restrictions on page loading, so mainstream front-end frameworks are moving towards SPA.
SPA, the abbreviation of Single Page Application, single page application, its purpose is that the entire application has only one html page, combined with the unified packaging idea of ​​building webpack, packages all static resource files into a js file, in the only html page Page reference, thus truly realizing the idea of ​​an html file and a js file completing an application.
SPA optimizes the performance of static loading, but an application still has many functional modules. Switching between functional modules becomes switching between components, so so far, basically the mainstream front-end frameworks will There are two concepts of routing and components, and the implementation ideas are consistent.

Routing reference and usage

//es5
var {Router, Route, hashHistory, Link, IndexRoute, browserHistory} = require("react-router");

//es6
import {Router, Route, hashHistory, Link, IndexRoute, browserHistory} from 'react-router';

//es5 和 es6 的使用都是一样的
<Link to="/">Root</Link>
<Router>
    <Route path=&#39;/&#39; component={RootComponent}/>
</Router>

//使用 `<script>` 标签 
<script src="../js/ReactRouter.js"></script>
<ReactRouter.Link to="/">Root</ReactRouter.Link>
<ReactRouter.Router>
    <ReactRouter.Route path=&#39;/&#39; component={RootComponent}/>
</ReactRouter.Router>
Copy after login

Routing components and attributes

  • is used to jump between routes, the function is the same Tags a. The

  • attribute to is equivalent to the href of the a tag.

  • ##page, the function is equivalent to page.

Router

  • is the outermost routing component, and there is only one in the entire Application.

  • Attribute

    history has two attribute values:

    • hashHistory The route will Switching through the hash part (#) of the URL is recommended.

    • ##

      The corresponding URL format is similar to example.com/#/some/path

    • browserHistory

      This situation requires server modification. Otherwise, the user directly requests a certain sub-route from the server, and a 404 error indicating that the web page cannot be found will be displayed.

    • ##
    • The corresponding URL format is similar to example.com/some/path.

    • Route component's properties

    Route
  • is a subcomponent of component

    Router, Route nesting can be achieved by nesting route.

    Attribute
  • path
  • : Specifies the matching rule of the route. This attribute can be omitted. In this case, the specified component will always be loaded regardless of whether the path matches or not.

    Attribute
  • component
  • : Refers to the corresponding component that will be rendered when the URL is mapped to the matching rule of the route.

    ##
  • When the URL is example.com/#/, the component RootComponent## will be rendered.
  • #

    When the URL is example.com/#/page1, the component Page1Component## will be rendered.
  • #Basic usage<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">import React from 'react' import ReactDOM from 'react-dom' import {Router, hashHistory, browserHistory} from 'react-router' const html = (     &lt;ul&gt;         &lt;li&gt;&lt;Link to=&quot;/&quot;&gt;Root&lt;/Link&gt;&lt;/li&gt;         &lt;li&gt;&lt;Link to=&quot;/page&quot;&gt;page&lt;/Link&gt;&lt;/li&gt;     &lt;/ul&gt; ) class RootComponent extends React.Component{     render(){         return (             &lt;p&gt;                 &lt;h1&gt;RootComponent&lt;/h1&gt;                 {html}             &lt;/p&gt;         )            } } class PageComponent extends React.Component{     render(){         return (             &lt;p&gt;                 &lt;h1&gt;PageComponent&lt;/h1&gt;                 {html}             &lt;/p&gt;         )            } } ReactDOM.render(     &lt;Router history={hashHistory}&gt;         &lt;Route path=&amp;#39;/&amp;#39; component={RootComponent}/&gt;         &lt;Route path=&amp;#39;/page&amp;#39; component={PageComponent}/&gt;     &lt;/Router&gt;,     document.getElementById('app') )</pre><div class="contentsignin">Copy after login</div></div>Effect preview

  • Routing parameters

Routing parameters are passed through the Route component path attribute to specify.

    The parameter value can be obtained through
  • this.props.params.paramName

    .

  • :paramName

  • Matches one part of the URL until it encounters the next /,?, #until.

    • .

    • Matching URL: /#/user/sam, the parameter sam must exist.

    • The value of this.props.params.name

      is sam.

import React from 'react'
import ReactDOM from 'react-dom'
import {Router, hashHistory, browserHistory} from 'react-router'

class UserComponent extends React.Component{
    render(){
        return (
            <p>
                <h3>UserComponent 单个参数 </h3>
                <p>路由规则:path='/user/:username'</p>
                <p>URL 映射:{this.props.location.pathname}</p>
                <p>username:{this.props.params.username}</p>
            </p>
        )       
    }
}
ReactDOM.render(
    <Router history={hashHistory}>
        <Route path=&#39;/user/:username&#39; component={UserComponent}/>
    </Router>,
    document.getElementById('app')
)
Copy after login
  • (:paramName)

    • 表示URL的这个部分是可选的。

    • <Route path="/order(/:orderid)">

    • 匹配 URL:/#/order,this.props.params.orderid 获取的值为 undefined。

    • 匹配 URL:/#/order/001,this.props.params.orderid获取参数的值为 001。

import React from 'react'
import ReactDOM from 'react-dom'
import {Router, hashHistory, browserHistory} from 'react-router'

class UserComponent extends React.Component{
    render(){
        return (
            <p>
                <h3>OrderComponent 可选参数 </h3>
                <p>路由规则:path='/order(/:orderid)'</p>
                <p>URL 映射:{this.props.location.pathname}</p>
                <p>orderid:{this.props.params.orderid}</p>
            </p>
        )       
    }
}
ReactDOM.render(
    <Router history={hashHistory}>
        <ReactRouter.Route path=&#39;/order(/:orderid)&#39; component={UserComponent}/>
    </Router>,
    document.getElementById('app')
)
Copy after login
  • *.*

    • 匹配任意字符,直到模式里面的下一个字符为止。匹配方式是非贪婪模式。

    • <Route path="/all1/*.*">

    • this.props.params 获取的参数为一个固定的对象: {splat: [*, *]}

    • 匹配 URL:/all1/001.jpg,参数为 {splat: ['001', 'jpg']}

    • 匹配 URL:/all1/001.html,参数为 {splat: ['001', 'html']}

  • *

    • 匹配任意字符,直到模式里面的下一个字符为止。匹配方式是非贪婪模式。

    • <Route path="/all2/*">

    • this.props.params 获取的参数为一个固定的对象: {splat: '*'}

    • 匹配 URL:/all2/,参数为 {splat: ''}

    • 匹配 URL:/all2/a,参数为 {splat: 'a'}

    • 匹配 URL:/all2/a/b,参数为 {splat: 'a/b'}

  • **

    • 匹配任意字符,直到下一个/、?、#为止。匹配方式是贪婪模式。

    • <Route path="/**/*.jpg">

    • this.props.params 获取的参数为一个固定的对象: {splat: [**, *]}

    • 匹配 URL:/all3/a/001.jpg,参数为 {splat: ['a', '001']}

    • 匹配 URL:/all3/a/b/001.jpg,参数为 {splat: ['a/b', '001']}

效果预览

IndexRoute

当访问一个嵌套路由时,指定默认显示的组件

AppComponent.js

import React from 'react'

export default class AppComponent extends React.Component{
    render(){
        return <p>{this.props.children}</p>
    }
}
Copy after login

LoginComponent.js

import React, {Component} from 'react'

export default class LoginComponent extends Component{
    login(){}
    render(){
        return <h1>Login</h1>
    }
}
Copy after login

HomeComponent.js

import React, {Component} from 'react'

export default class HomeComponent extends Component{
    login(){}
    render(){
        return <h1>Home</h1>
    }
}
Copy after login

Router.js

import React from 'react'
import {Route, IndexRoute} from 'react-router'

import AppComponent from '../components/app/app'
import HomeComponent from '../components/home/home'
import LoginComponent from '../components/login/login'

const routes = (
    <Route path="/" component={AppComponent}>
        <IndexRoute component={HomeComponent} />
        <Route path="login" component={LoginComponent} />
        <Route path="home" component={HomeComponent} />
    </Route>
)

export default routes;
Copy after login
  • 如果没有加IndexRoute,则在访问 http://localhost/#/ 时页面是空白的

  • 访问 http://localhost/#/login 才会显示内容

  • 加上 IndexRoute,在访问http://localhost/#/时会默认渲染HomeComponent

模块化

可利用组件Router的属性routes来实现组件模块化

router.js

import React from 'react'
import ReactDOM from 'react-dom'

import {Route, Router, IndexRoute, hashHistory} from 'react-router'

import AppComponent from '../components/app/app'
import HomeComponent from '../components/home/home'
import LoginComponent from '../components/login/login'

const routes = (
    <Route path="/" component={AppComponent}>
        <IndexRoute component={HomeComponent} />
        <Route path="login" component={LoginComponent} />
        <Route path="home" component={HomeComponent} />
    </Route>
)

ReactDOM.render(
    <Router history={hashHistory} routes={routes} />,
    document.getElementById('app')
)
Copy after login

编程式导航

  • 普通跳转 this.props.router.push('/home/cnode')

  • 带参数跳转this.props.router.push({pathname: '/home/cnode', query: {name: 'tom'}})

路由钩子函数

每个路由都有enterleave两个钩子函数,分别代表用户进入时和离开时触发。

onEnter

进入路由/home前会先触发onEnter方法,如果已登录,则直接next()正常进入目标路由,否则就先修改目标路径replace({ pathname: 'login' }),再next()跳转。

let isLogin = (nextState, replace, next) => {
    if(window.localStorage.getItem('auth') == 'admin'){
        next()
    } else {
        replace({ pathname: 'login' })
        next();
    }
    
}
const routes = (
    <Route path="/" component={AppComponent}>
        <Route path="login" component={LoginComponent} />
        <Route path="home" component={HomeComponent} onEnter={isLogin}/>
    </Route>
)
Copy after login

onLeave

对应的setRouteLeaveHook方法,如果return true则正常离开,否则则还是停留在原路由

import React from 'react'
import {Link} from 'react-router'

export default class Component1 extends React.Component{
    componentDidMount(){
        this.props.router.setRouteLeaveHook(
            this.props.route,
            this.routerWillLeave
        )
    }
    routerWillLeave(){
        return '确认要离开?'
    }
    render(){
        return (
            <p>
                <Link to="/login">Login</Ling>
            </p>
        )
    }
}
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

PromiseA+的实现步骤详解

react实现选中li高亮步骤详解

The above is the detailed content of Detailed explanation of routing in React. For more information, please follow other related articles on the PHP Chinese website!

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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP, Vue and React: How to choose the most suitable front-end framework? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

How to use Golang functions to handle web request routing How to use Golang functions to handle web request routing May 02, 2024 am 10:18 AM

In Golang, using functions to handle web request routing is an extensible and modular method of building APIs. It involves the following steps: Install the HTTP router library. Create a router. Define path patterns and handler functions for routes. Write handler functions to handle requests and return responses. Run the router using an HTTP server. This process allows for a modular approach when handling incoming requests, improving reusability, maintainability, and testability.

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

Detailed explanation of how to operate hidden apps on Black Shark phone Detailed explanation of how to operate hidden apps on Black Shark phone Mar 24, 2024 pm 12:09 PM

Detailed explanation of how to operate hidden applications on Black Shark mobile phones As mobile phone functions continue to improve, modern people’s needs for mobile phones are becoming more and more diverse. Some people may save some private information or personal photos on their mobile phones. In order to protect privacy and security, many mobile phones provide the function of hiding applications. As a mobile phone specially designed for gamers, Black Shark also provides users with the function of hiding applications. Let’s introduce in detail the operation method of hidden applications on Black Shark mobile phone. Step 1: Open the “Settings” interface. First, the user needs to open the Black Shark mobile phone.

Go language memory management detailed explanation Go language memory management detailed explanation Mar 28, 2024 am 09:18 AM

Detailed explanation of Go language memory management Go language, as a modern programming language, comes with a garbage collector, which eliminates the need for developers to manually manage memory and greatly simplifies the complexity of memory management. This article will introduce the memory management mechanism of Go language in detail and illustrate it through specific code examples. Memory management principle The memory management of Go language mainly relies on the garbage collector for automatic memory recycling. The garbage collector (GarbageCollector) regularly checks memory blocks that are no longer used in the program and recycles them.

See all articles