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!

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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.


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

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
