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>Root <router> <route></route> </router> //使用 `<script>` 标签 <script src="../js/ReactRouter.js"></script> <reactrouter.link>Root</reactrouter.link> <reactrouter.router> <reactrouter.route></reactrouter.route> </reactrouter.router>
Routing components and attributes
Link
is used to jump between routes, the function is the same Tags
a
. Theattribute
to
is equivalent to thehref
of thea
tag.##page
, the function is equivalent to
page.
- 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
- is a subcomponent of component
Router
Attribute, Route nesting can be achieved by nesting
route.
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
) } } class PageComponent extends React.Component{ render(){ return (<pre class="brush:php;toolbar:false">import React from 'react' import ReactDOM from 'react-dom' import {Router, hashHistory, browserHistory} from 'react-router' const html = ( </pre> <ul> <li> <link>Root</li> <li> <link>page</li> </ul> ) class RootComponent extends React.Component{ render(){ return ( <p> </p> <h1 id="RootComponent">RootComponent</h1> {html}
PageComponent
{html} ) } } ReactDOM.render( 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> </p><h3 id="UserComponent-单个参数">UserComponent 单个参数 </h3> <p>路由规则:path='/user/:username'</p> <p>URL 映射:{this.props.location.pathname}</p> <p>username:{this.props.params.username}</p> ) } } ReactDOM.render( <router> <route></route> </router>, document.getElementById('app') )
(:paramName)
表示URL的这个部分是可选的。
<route path="/order(/:orderid)"></route>
。匹配 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> </p><h3 id="OrderComponent-可选参数">OrderComponent 可选参数 </h3> <p>路由规则:path='/order(/:orderid)'</p> <p>URL 映射:{this.props.location.pathname}</p> <p>orderid:{this.props.params.orderid}</p> ) } } ReactDOM.render( <router> <reactrouter.route></reactrouter.route> </router>, document.getElementById('app') )
*.*
匹配任意字符,直到模式里面的下一个字符为止。匹配方式是非贪婪模式。
<route path="/all1/*.*"></route>
。this.props.params
获取的参数为一个固定的对象:{splat: [*, *]}
。匹配 URL:/all1/001.jpg,参数为
{splat: ['001', 'jpg']}
。匹配 URL:/all1/001.html,参数为
{splat: ['001', 'html']}
。*
匹配任意字符,直到模式里面的下一个字符为止。匹配方式是非贪婪模式。
<route path="/all2/*"></route>
。this.props.params
获取的参数为一个固定的对象:{splat: '*'}
。匹配 URL:/all2/,参数为
{splat: ''}
。匹配 URL:/all2/a,参数为
{splat: 'a'}
。匹配 URL:/all2/a/b,参数为
{splat: 'a/b'}
。**
匹配任意字符,直到下一个/、?、#为止。匹配方式是贪婪模式。
<route path="/**/*.jpg"></route>
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> } }
LoginComponent.js
import React, {Component} from 'react' export default class LoginComponent extends Component{ login(){} render(){ return <h1 id="Login">Login</h1> } }
HomeComponent.js
import React, {Component} from 'react' export default class HomeComponent extends Component{ login(){} render(){ return <h1 id="Home">Home</h1> } }
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> <indexroute></indexroute> <route></route> <route></route> </route> ) export default routes;
如果没有加
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> <indexroute></indexroute> <route></route> <route></route> </route> ) ReactDOM.render( <router></router>, document.getElementById('app') )
编程式导航
普通跳转
this.props.router.push('/home/cnode')
带参数跳转
this.props.router.push({pathname: '/home/cnode', query: {name: 'tom'}})
路由钩子函数
每个路由都有enter
和leave
两个钩子函数,分别代表用户进入时和离开时触发。
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> <route></route> <route></route> </route> )
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>Login </p> ) } }
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
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!

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver CS6
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools
