This time I will bring you how to use React Router v4 from scratch. What are the precautions for using React Router v4 from scratch? 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 help assistant
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 both have to
cite ? 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;
StaticRouter>
:从不会改变地址;
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中文网其它相关文章!
推荐阅读:
How to correctly solve cross-domain problems encountered in Vue projects
How to use vue-cli axios request method and cross-domain processing
The above is the detailed content of Using React Router v4 from scratch. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

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.


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

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.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment