Home Web Front-end JS Tutorial Detailed explanation of React routing management and use of React Router

Detailed explanation of React routing management and use of React Router

May 30, 2018 pm 01:55 PM
react router routing

This time I will bring you a detailed explanation of React routing management and the use of React Router. What are the precautions for React routing management and the use of React Router? Here are practical cases, let’s take a look.

What does React Router do? The official introduction is:

A complete routing library for React, keeps your UI in sync with the URL. It has a simple API with Powerful features like lazy code loading, dynamic route matching, and location transition handling built right in. Make the URL your first thought, not an after-thought. Synchronization, powerful features such as code lazy loading, dynamic route matching, path transition processing, etc. can be realized through a simple API.

The following are some usages of React Router:

A simple rendering Route

There is one thing to keep in mind, Router As a React component, it can be rendered.

// ...
import { Router, Route, hashHistory } from 'react-router'
render((
 <Router history={hashHistory}>
  <Route path="/" component={App}/>
 </Router>
), document.getElementById('app'))
Copy after login
HashHistory is used here - it manages the routing history and the hash part of the URL.

Add more routes and specify their corresponding components

import About from './modules/About'
import Repos from './modules/Repos'
render((
 <Router history={hashHistory}>
  <Route path="/" component={App}/>
  <Route path="/repos" component={Repos}/>
  <Route path="/about" component={About}/>
 </Router>
), document.getElementById('app'))
Copy after login

二Link

// modules/App.js
import React from 'react'
import { Link } from 'react-router'
export default React.createClass({
 render() {
  return (
   <p>
    <h1>React Router Tutorial</h1>
    <ul role="nav">
     <li><Link to="/about">About</Link></li>
     <li><Link to="/repos">Repos</Link></li>
    </ul>
   </p>
  )
 }
})
Copy after login
Link is used here Component, which can render out links and use the to attribute to point to the corresponding route.

Three nested routes

If we want to add a navigation bar, it needs to exist on every page. If there is no router, we need to encapsulate each nav component and reference and render it in each page component. As the application grows the code becomes redundant. React-router provides another way to nest shared UI components.

In fact, our app is a series of nested boxes, and the corresponding url can also illustrate this nested relationship:

<App>    {/* url /     */}
 <Repos>  {/* url /repos   */}
  <Repo/> {/* url /repos/123 */}
 </Repos>
</App>
Copy after login
Therefore, we can use the handle

component Nest

into the public component App so that the navigation bar Nav and other public parts on the App component can be shared:

// index.js
// ...
render((
 <Router history={hashHistory}>
  <Route path="/" component={App}>
   {/* 注意这里把两个子组件放在Route里嵌套在了App的Route里/}
   <Route path="/repos" component={Repos}/>
   <Route path="/about" component={About}/>
  </Route>
 </Router>
), document.getElementById('app'))
Copy after login
Next, render the children in the App:
// modules/App.js
// ...
 render() {
  return (
   <p>
    <h1>React Router Tutorial</h1>
    <ul role="nav">
     <li><Link to="/about">About</Link></li>
     <li><Link to="/repos">Repos</Link></li>
    </ul>
    {/* 注意这里将子组件渲染出来 */}
    {this.props.children}
   </p>
  )
 }
// ...
Copy after login

Four valid links

One of the differences between the Link component and the a tag is that Link can know whether the path it points to is a valid route.

<li><Link to="/about" activeStyle={{ color: &#39;red&#39; }}>About</Link></li>
<li><Link to="/repos" activeStyle={{ color: &#39;red&#39; }}>Repos</Link></li>
Copy after login
You can use activeStyle to specify the style of an effective link, or you can use activeClassName to specify the style class of an effective link.

Most of the time, we don’t need to know whether the link is valid, but this feature is very important in navigation. For example: you can display only legal routing links in the navigation bar.

// modules/NavLink.js
import React from 'react'
import { Link } from 'react-router'
export default React.createClass({
 render() {
  return <Link {...this.props} activeClassName="active"/>
 }
})
Copy after login
// modules/App.js
import NavLink from './NavLink'
// ...
<li><NavLink to="/about">About</NavLink></li>
<li><NavLink to="/repos">Repos</NavLink></li>
Copy after login
You can specify in NavLink that only .active links will be displayed, so that if the route is invalid, the link will not appear in the navigation bar.

Five URL parameters

Consider the following url:

/repos/reactjs/react-router

/ repos/facebook/react

They may correspond to this form:

/repos/:userName/:repoName

: followed by variable parameters

The variable parameters in

url

can be obtained through this.props.params[paramsName]:

// modules/Repo.js
import React from 'react'
export default React.createClass({
 render() {
  return (
   <p>
{/* 注意这里通过this.props.params.repoName 获取到url中的repoName参数的值 */}
    <h2>{this.props.params.repoName}</h2>
   </p>
  )
 }
})
Copy after login
// index.js
// ...
// import Repo
import Repo from './modules/Repo'
render((
 <Router history={hashHistory}>
  <Route path="/" component={App}>
   <Route path="/repos" component={Repos}/>
   {/* 注意这里的路径 带了 :参数 */}
   <Route path="/repos/:userName/:repoName" component={Repo}/>
   <Route path="/about" component={About}/>
  </Route>
 </Router>
), document.getElementById('app'))
Copy after login
Next visit /repos/reactjs/react-router and /repos/ facebook/react will see different content.

6 Default Route

// index.js
import { Router, Route, hashHistory, IndexRoute } from 'react-router'
// and the Home component
import Home from './modules/Home'
// ...
render((
 <Router history={hashHistory}>
  <Route path="/" component={App}>
   {/* 注意这里* /}
   <IndexRoute component={Home}/>
   <Route path="/repos" component={Repos}>
    <Route path="/repos/:userName/:repoName" component={Repo}/>
   </Route>
   <Route path="/about" component={About}/>
  </Route>
 </Router>
), document.getElementById('app'))
Copy after login
IndexRoute is added here to specify the default path / corresponding component. Note that it has no path attribute value.

Similarly, there is also the default link component IndexLink. ,

7 Using Browser History

The previous example has always used hashHistory, because it can always run, but a better way is Using Browser History, it does not rely on hashed ports (#).

First you need to change index.js:

// ...
// bring in `browserHistory` instead of `hashHistory`
import { Router, Route, browserHistory, IndexRoute } from 'react-router'
render((
{/* 注意这里 */}
 <Router history={browserHistory}>
  {/* ... */}
 </Router>
), document.getElementById('app'))
Copy after login
Secondly you need to modify the local service configuration of webpack, open package.json and add –history-api-fallback:

复制代码 代码如下:

"start": "webpack-dev-server --inline --content-base . --history-api-fallback"

最后需要在 index.html中 将文件的路径改为相对路径:

<!-- index.html -->
<!-- index.css 改为 /index.css -->
<link rel="stylesheet" href="/index.css" rel="external nofollow" >
<!-- bundle.js 改为 /bundle.js -->
<script src="/bundle.js"></script>
Copy after login

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

推荐阅读:

如何使用AngularJS模态框模板ngDialog

使用Vue.js下载方式案例详解

The above is the detailed content of Detailed explanation of React routing management and use of React Router. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to build a real-time chat app with React and WebSocket How to build a real-time chat app with React and WebSocket Sep 26, 2023 pm 07:46 PM

How to build a real-time chat application using React and WebSocket Introduction: With the rapid development of the Internet, real-time communication has attracted more and more attention. Live chat apps have become an integral part of modern social and work life. This article will introduce how to build a simple real-time chat application using React and WebSocket, and provide specific code examples. 1. Technical preparation Before starting to build a real-time chat application, we need to prepare the following technologies and tools: React: one for building

Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Sep 28, 2023 am 10:48 AM

React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

How to build simple and easy-to-use web applications with React and Flask How to build simple and easy-to-use web applications with React and Flask Sep 27, 2023 am 11:09 AM

How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

How to build a reliable messaging app with React and RabbitMQ How to build a reliable messaging app with React and RabbitMQ Sep 28, 2023 pm 08:24 PM

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

React Router User Guide: How to implement front-end routing control React Router User Guide: How to implement front-end routing control Sep 29, 2023 pm 05:45 PM

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

Java Apache Camel: Building a flexible and efficient service-oriented architecture Java Apache Camel: Building a flexible and efficient service-oriented architecture Feb 19, 2024 pm 04:12 PM

Apache Camel is an Enterprise Service Bus (ESB)-based integration framework that can easily integrate disparate applications, services, and data sources to automate complex business processes. ApacheCamel uses route-based configuration to easily define and manage integration processes. Key features of ApacheCamel include: Flexibility: ApacheCamel can be easily integrated with a variety of applications, services, and data sources. It supports multiple protocols, including HTTP, JMS, SOAP, FTP, etc. Efficiency: ApacheCamel is very efficient, it can handle a large number of messages. It uses an asynchronous messaging mechanism, which improves performance. Expandable

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.

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.

See all articles