


Detailed explanation of React routing management and use of React Router
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:
The following are some usages of React Router: A simple rendering RouteA 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.
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'))
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'))
// 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>
)
}
})
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>
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'))
// 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> ) } // ...
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: 'red' }}>About</Link></li> <li><Link to="/repos" activeStyle={{ color: 'red' }}>Repos</Link></li>
// modules/NavLink.js import React from 'react' import { Link } from 'react-router' export default React.createClass({ render() { return <Link {...this.props} activeClassName="active"/> } })
// modules/App.js import NavLink from './NavLink' // ... <li><NavLink to="/about">About</NavLink></li> <li><NavLink to="/repos">Repos</NavLink></li>
Consider the following url:
/repos/reactjs/react-router/ repos/facebook/react
They may correspond to this form:
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> ) } })
// 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'))
// 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'))
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'))
复制代码 代码如下:
"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>
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

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

In modern web applications, implementing web page navigation and routing is a very important part. Using JavaScript functions to implement this function can make our web applications more flexible, scalable and user-friendly. This article will introduce how to use JavaScript functions to implement web page navigation and routing, and provide specific code examples. Implementing web page navigation For a web application, web page navigation is the most frequently operated part by users. When a user clicks on the page

Uniapp is a cross-end framework based on Vue.js. It supports one-time writing and generates multi-end applications such as H5, mini programs, and APPs at the same time. It pays great attention to performance and development efficiency during the development process. In Uniapp, the dynamic addition and deletion of routes is a problem that is often encountered during the development process. Therefore, this article will introduce the dynamic addition and deletion of routes in Uniapp and provide specific code examples. 1. Dynamic addition of routes Dynamic addition of routes can be done according to actual needs when the page is loaded or after user operation.

Tips for using route interceptors in uniapp In uniapp development, route interceptors are a very common function. Route interceptors allow us to perform some specific operations before routing jumps, such as permission verification, page passing parameters, etc. In this article, we will introduce the tips for using route interceptors in uniapp and provide specific code examples. Create a route interceptor First, we need to create a route interceptor in the uniapp project. The creation method is as follows: Create an inter in the project root directory

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.

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.
