Detailed explanation of using React Router v4
This time I will bring you a detailed explanation of the use of React Router v4, what are the precautions when using React Router v4, the following is a practical case, let's take a look.
There are rumors in the world that the official version is currently maintained at the same time, 2.x and 4.x. (ヾ(。ꏿ﹏ꏿ)ノ゙Hey, at this moment, I believe that you who are as smart as me will also find out, where has ReactRouter v3 gone? Lost it all?? Bala is out of trouble??? Dare you give me a perfect one? Explanation! ?) In fact, version 3.x does not introduce any new features compared to version 2.x, it just removes the warnings of some obsolete APIs in version 2.x. According to the plan, when new projects without historical baggage want to use the stable version of ReactRouter, they should use ReactRouter 3.x. The 3.x version is currently still in the beta stage, but will be officially released before the 4.x version. If you are already using version 2.x, upgrading to 3.x will not require any additional code changes.
Polite introduction
React Router V4 has fundamental changes compared to the previous three versions. The first is to follow# The API design concept of ##Just Component, and secondly, the API aspect has also been streamlined a lot, which reduces the difficulty of learning for novices, but if it is a reconstruction of the previous project, well, there is simply nothing to say. The main features of this upgrade are as follows:
- Declarative
- Composability
Everything is a component. Therefore, the upgraded Route, Link, Switch, etc. are all common components.
React Router V4 manages multiple Repositories based on Lerna. Included in this code base:- react-router React Router core
- react-router-dom React Router for DOM binding
- react-router-native React Router for React Native
- react-router-redux Integration of React Router and Redux
- react-router-config Static routing configuration helper
Initial introduction of the plug-in
Usually we are in React In use, two packages are generally introduced,react and
react-dom, then
react-router and
react-router-dom Do they need to be quoted from both?
Attention, there is high energy ahead, the first pit to get started is right here. They only need to reference one of them. The difference is that the latter has more DOM class components like <link> than the former. So we only need to quote the
react-router-dom package and it's OK. Of course, if paired with
redux, you also need to use
react-router-redux.
Introduction to the main components
In the API version before 4.0, the children of the component can only be the various components provided by React Router. Various components, such as
, etc. In React Router 4, you can put various components and labels into the
component, and its role is more like the
in Redux. . **The difference is that
is used to keep updated with the store, while
is used to keep synchronized with the location. **An example is as follows:
// 示例1
<router>
<p>
</p>
<ul>
<li>
<link>首页</li>
<li>
<link>关于</li>
<li>
<link>主题列表</li>
</ul>
<hr>
<route></route>
<route></route>
<route></route>
</router>
: Use the history API provided by HTML5 to keep the UI and URL synchronized;
: Use the hash of the URL (for example: window.location.hash) to keep the UI and URL in sync;
: can save your " URL" history (does not read or write the address bar);
- ##
: Provide routing support for using React Native;
- Static
Router><a href="http://www.php.cn/wiki/188.html" target="_blank">: Never change the address;</a>
TIPS:算是第二坑吧,和之前的Router不一样,这里 <router></router>
组件下只允许存在一个子元素,如存在多个则会报错。
反面典型在这里:
<router> <ul> <li> <link>首页</li> <li> <link>关于</li> <li> <link>主题列表</li> </ul> <hr> <route></route> <route></route> <route></route> </router>
没错,示例2在没有 <p></p>
爸爸的保护下,会报如下异常信息:
我们知道,Route组件主要的作用就是当一个location匹配路由的path时,渲染某些UI。示例如下:
<router> <p> <route></route> <route></route> </p> </router> // 如果应用的地址是/,那么相应的UI会类似这个样子: <p> <home></home> </p> // 如果应用的地址是/news,那么相应的UI就会成为这个样子: <p> <newsfeed></newsfeed> </p>
<route></route>
组件有如下属性:
path(string): 路由匹配路径。(没有path属性的Route 总是会 匹配);
exact(bool):为true时,则要求路径与location.pathname必须完全匹配;
strict(bool):true的时候,有结尾斜线的路径只能匹配有斜线的location.pathname;
再次奉上两个鲜活的例子:
exact配置:
路径 | location.pathname | exact | 是否匹配 |
---|---|---|---|
/one | /one/two | true | 否 |
/one | /one/two | false | 是 |
strict配置:
路径 | location.pathname | strict | 是否匹配 |
---|---|---|---|
/one/ | /one | true | 否 |
/one/ | /one/ | true | 是 |
/one/ | /one/two | true | 是 |
同时,新版的路由为 <route></route>
提供了三种渲染内容的方法:
<route component></route>
:在地址匹配的时候React的组件才会被渲染,route props也会随着一起被渲染;<route render></route>
:这种方式对于内联渲染和包装组件却不引起意料之外的重新挂载特别方便;<route children></route>
:与render属性的工作方式基本一样,除了它是不管地址匹配与否都会被调用;
第一种方式没啥可说的,和之前一样,这里我们重点看下 <route render></route>
的渲染方式:
// 行内渲染示例 <route> <p>Home</p>}/> // 包装/合成 const FadingRoute = ({ component: Component, ...rest }) => ( <route> ( <fadein> <component></component> </fadein> )}/> ) <fadingroute></fadingroute></route></route>
TIPS: 第三坑! <route component></route>
的优先级要比 <route render></route>
高,所以不要在同一个 <route></route>
中同时使用这两个属性。
和之前版本没太大区别,重点看下组件属性:
to(string/object):要跳转的路径或地址;
replace(bool): 为 true 时 ,点击链接后将使用新地址替换掉访问历史记录里面的原地址; 为 false 时 ,点击链接后将在原有访问历史记录的基础上添加一个新的纪录。 默认为 false ;
示例如下:
// Link组件示例 // to为string <link>关于 // to为obj <link> // replace <link>
<navlink></navlink>
是 <link>
的一个特定版本, 会在匹配上当前 URL 的时候会给已经渲染的元素添加样式参数,组件属性:
activeClassName(string):设置选中样式,默认值为 active;
activeStyle(object):当元素被选中时, 为此元素添加样式;
exact(bool):为 true 时, 只有当地址完全匹配 class 和 style 才会应用;
strict(bool):为 true 时,在确定位置是否与当前 URL 匹配时,将考虑位置 pathname 后的斜线; isActive(func):判断链接是否激活的额外逻辑的功能;
从这里我们也可以看出,新版本的路由在组件化上面确实下了不少功夫,来看看NavLink的使用示例:
// activeClassName选中时样式为selected <navlink>FAQs</navlink> // 选中时样式为activeStyle的样式设置 <navlink>FAQs</navlink> // 当event id为奇数的时候,激活链接 const oddEvent = (match, location) => { if (!match) { return false } const eventID = parseInt(match.params.eventID) return !isNaN(eventID) && eventID % 2 === 1 } <navlink>Event 123</navlink>
该组件用来渲染匹配地址的第一个 <route></route>
或者 <redirect></redirect>
。那么它与使用一堆route又有什么区别呢?
<switch></switch>
的独特之处是独它仅仅渲染一个路由。相反地,每一个包含匹配地址(location)的 <route></route>
都会被渲染。思考下面的代码:
<route></route> <route></route> <route></route>
如果现在的URL是 /about
,那么 <about></about>
, <user></user>
, 还有 <nomatch></nomatch>
都会被渲染,因为它们都与路径(path)匹配。这种设计,允许我们以多种方式将多个 <route></route>
组合到我们的应用程序中,例如侧栏(sidebars),面包屑(breadcrumbs),bootstrap tabs等等。 然而,偶尔我们只想选择一个 <route></route>
来渲染。如果我们现在处于 /about
,我们也不希望匹配 /:user
(或者显示我们的 “404” 页面 )。以下是使用 Switch 的方法来实现:
<switch> <route></route> <route></route> <route></route> <route></route> </switch>
现在,如果我们处于 /about
, <switch></switch>
将开始寻找匹配的 <route></route>
。 <route path="/about"></route>
将被匹配, <switch></switch>
将停止寻找匹配并渲染 <about></about>
。同样,如果我们处于 /michael
, <user></user>
将被渲染。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
What are the basic algorithms of Js
The above is the detailed content of Detailed explanation of using React Router v4. For more information, please follow other related articles on the PHP Chinese website!

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.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.


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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use