Detailed explanation of steps to use React-router v4
This time I will bring you a detailed explanation of the steps to use React-router v4. What are the precautions when using React-router v4? The following is a practical case, let’s take a look.
Perhaps the best way to learn react-router is to use react-router-dom v4 to write a multi-page react application. This react application will include login, registration, homepage, contact and other pages. But first let's take a look at the concept of react router v4 and how it differs from v3.
React router v4 vs v3
v4 is a rewrite of react router, so it has many differences from v3. The main ones are:
In react router v4, routing is no longer centralized. It becomes part of the application layout and UI.
The router used by the browser is in
react-router-dom
. Therefore, when using it in the browser, you only need to importreact-router-dom
.New concepts
BrowerRouter
andHashRouter
. They each serve different situations. See below for details.No longer use
{props.children}
to handle nested routes.v4 routing is no longer exclusive by default and will have multiple matches. v3 is exclusive by default, and only one match will be used.
react-router-dom
is used in react-router for browsers. react-router
is divided into the following parts:
react-router is a common part for browsers and native applications.
react-router-dom is for browsers.
react-router-native is for native applications.
React-router vs react-router-dom vs react-router-native
react-router
is the core part. react-router-dom
Provides customized components required for browser use. react-router-native
specifically provides the parts that need to be used in native mobile applications. Therefore, if you implement browser development in this example, you only need to install react-router-dom
.
Installation
As mentioned above, we use react to develop web applications, so we only need to install react-router-dom
.
npm install react-router-dom --save
Understand and use react-router
BrowserRouter
, which is the implementation of theRouter
interface. Make the page and browser history consistent. For example:window.location
.HashRouter
is the same as above, except that it uses the hash part of the url, such as:window.location.hash
.MemoryRouter
,##NativeRouter
, handle routing in react native.
Static<a href="http://www.php.cn/wiki/188.html" target="_blank">Router</a>, handles static routing, the same as v3.
and
can be used in the browser. If you are using a non-static site and want to handle various URLs, then you need to use
BrowserRouter. On the contrary, if your server only handles static URLs, use
HashRouter.
Route component.
Route component can use the following attributes:
- path attribute,
- component attribute, its value is a component. This component will be drawn after
path
is successfully matched.
- exact attribute, this attribute is used to indicate whether this route is an exclusive match.
- strict attribute, this attribute specifies that the path only matches paths ending with a slash.
还有其他的一些属性,可以用来代替component
属性。
render属性,一个返回React组件的方法。传说中的rencer-prop就是从这里来的。
children属性,返回一个React组件的方法。只不过这个总是会绘制,即使没有匹配的路径的时候。
多数的时候是用component
属性就可以满足。但是,某些情况下你不得不使用render
或children
属性。
match
location
history
如:
使用组件:
<route></route>
使用render
属性实现内联绘制:
<route><p>HomePage</p>} /></route>
来看哥更复杂的:
const FadingRoute = ({ component, ...rest }) => ( <route> ( <fadein> <componnet></componnet> </fadein> )} /> ) <fadingroute></fadingroute></route>
使用children
:
更多关于react-router v4如何匹配路径的内容,请移步这里。
URL / Path / Route的参数
通常情况下,我们都会在路径里添加参数。这样方便在不同的组件之间传递一些必要的数据。那么我们如何才能获取到这些传递的参数,并传递给组件中呢?我们只需要在路径的最后加上/:param
。如:
<route></route> const HomePage = ({match}) => (
parameter => {match.params.param1} );
一旦有路径可以匹配成功,那么就会穿件一个拥有如下属性的对象,并传入绘制的组件里:
url: 匹配的url。
path:就是path。
isExact:如果
path
和当前的widnow.location
的path部分完全相同的话。params:在URL里包含的参数。
理解并使用Link
Link
是react router v4特有的一个组件。是用来代替上一版的anchor link。使用Link
可以在React应用的不同页面之间跳转。与unclor会重新加载整个页面不同,Link
只会重新加载页面里和当前url可以匹配的部分。
Link
组件需要用到to
属性,这个属性的值就是react router要跳转到的地址。如:
import { Link } from 'react-router-dom'; const Nav = () => ( <link>Home );
当被点击的时候,会跳转到路径:/
。
to
属性的值可以是一个字符串,也可以是一个location(pathname, hash, state和search)对象。比如:
<link>
Link
也可以使用replace
属性,如果点击的话,那么history里的当前领会被replace。
<link>和
NavLink
是Link
的一个子类,在Link组件的基础上增加了绘制组件的样式,比如:
<navlink> My Profile </navlink>
使用react router dom实现你的第一个demo
现在我们用react router dom来实现第一个demo。
首先,引入必要的组件。比如:Route
和BrowserRouter
。
import { BrowserRouter, Route } from 'react-router-dom';
接下来,我们创建一些组件和一些Html标签。同时我们用react router v4里的Link
和NavLink
组件。
const BaseLayout = () => (
React Router v4 Browser Example
<route></route> <route></route> <route></route> <route></route> <route></route> <route></route>
);
然后我们来创建需要的组件:
const HomePage = () => <p>This is a Home Page</p> const LoginPage = () => <p>This is a Login Page</p> const RegisterPage = () => <p>This is a Register Page</p> const ProfilePage = () => <p>This is a Profile Page</p> const AboutPage = () => <p>This is a About Page</p> const ContactPage = () => <p>This is a Contact Page</p>
最后,写App
组件。
const App = () => ( <browserrouter> <baselayout></baselayout> </browserrouter> ) render(<app></app>, document.getElementById('root'));
如你所见,react router v4的组件还非常的易用的。
理解和使用非排他的路由
在上例中,我们在HomePage
组件的路由里使用了属性exact
。
<route></route>
这是因为v4中的路由默认都是非排他的,这一点和v3的实现思路截然不同。如果没有exact
属性,HomePage
组件和其他的组件就会同事绘制在页面上。
如,当用户点了登录连接以后,"/"
和"/login"
都满足匹配条件,对应的登录组件和Home组件就会同时出现在界面上。但是,这不是我们期待的结果,所以我们要给"/"
path加上exact
属性。
现在我们来看看非排他的路由有什么优点。假如我们有一个子菜单组件需要显示在profile页面出现的时候也出现。我们可以简单的修改BasicLayout
来实现。
const BaseLayout = () => ();
React Router v4 Browser Example
这样我们就会看到对应于"/me"
路径的组件都绘制出来了。这就是非排他路由的好处。
理解排他路由
排他路由是react router v3的默认实现。只有第一个匹配的路由对应的组件会被绘制。这一点也可以用react router v4的Switch
组件来实现。在Switch
组件中,只有第一个匹配的路由<route></route>
或者<redirect></redirect>
会被绘制:
import { Switch, Route } from 'react-router';<route></route> <route></route> <route></route> <route></route>
浏览器历史
react router v4中,提供了一个history
对象。这个对象包含了多个api,可以用来操作浏览器历史等。
你也可以在React应用里使用history
对象的方法:
history.push("/my-path") history.replace("/my-path")
用另外的方法可以写成:
<link> <redirect></redirect>
使用组件实现重定向
无论何时你要重定向到另外一个地址的时候,都可以使用Redirect
组件:
<redirect></redirect>
或者,更为简单的:
<redirect></redirect>
最后
react router v4让开发react应用变得更加的简单。让react应用内的页面跳转更加简单。你只需要声明一个BrowserRouter
或者HashRouter
,然后在它的内部放上一系列的Route
组件,这些主键只要包含path
和component
属性。无论何时有了匹配的路由,那么它就会进行非排他的绘制(所有匹配的路由都会绘制)。你也可以把Route
放在Switch
组件里来实现排他的绘制(只有第一个匹配的路由会被绘制)。你可以在路径中传递参数,match
对象会保留这些参数。最后,所有在web中使用的路由组件都包含在react-router-dom
中。只需要引入react-router-dom
就可以使用。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed explanation of steps to use React-router v4. For more information, please follow other related articles on the PHP Chinese website!

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

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

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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