Using React Router v4 from scratch
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<Router> component can only be the various components provided by React Router. Various components, such as
<Route>, , etc. In React Router 4, you can put various components and labels into the
<Router> component, and its role is more like the
in Redux. . **The difference is that
is used to keep updated with the store, while
<Router> is used to keep synchronized with the location. **An example is as follows:
// 示例1 <Router> <p> <ul> <li><Link to="/">首页</Link></li> <li><Link to="/about">关于</Link></li> <li><Link to="/topics">主题列表</Link></li> </ul> <hr/> <Route exact path="/" component={Home}/> <Route path="/about" component={About}/> <Route path="/topics" component={Topics}/> </p> </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;
<<a href="http://www.php.cn/wiki/188.html" target="_blank">Static</a>Router>
:从不会改变地址;
TIPS:算是第二坑吧,和之前的Router不一样,这里 <Router>
组件下只允许存在一个子元素,如存在多个则会报错。
反面典型在这里:
<Router> <ul> <li><Link to="/">首页</Link></li> <li><Link to="/about">关于</Link></li> <li><Link to="/topics">主题列表</Link></li> </ul> <hr/> <Route exact path="/" component={Home}/> <Route path="/about" component={About}/> <Route path="/topics" component={Topics}/> </Router>
没错,示例2在没有 <p>
爸爸的保护下,会报如下异常信息:
我们知道,Route组件主要的作用就是当一个location匹配路由的path时,渲染某些UI。示例如下:
<Router> <p> <Route exact path="/" component={Home}/> <Route path="/news" component={NewsFeed}/> </p> </Router> // 如果应用的地址是/,那么相应的UI会类似这个样子: <p> <Home/> </p> // 如果应用的地址是/news,那么相应的UI就会成为这个样子: <p> <NewsFeed/> </p>
<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 component>
:在地址匹配的时候React的组件才会被渲染,route props也会随着一起被渲染;<Route render>
:这种方式对于内联渲染和包装组件却不引起意料之外的重新挂载特别方便;<Route children>
:与render属性的工作方式基本一样,除了它是不管地址匹配与否都会被调用;
第一种方式没啥可说的,和之前一样,这里我们重点看下 <Route render>
的渲染方式:
// 行内渲染示例 <Route path="/home" render={() => <p>Home</p>}/> // 包装/合成 const FadingRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={props => ( <FadeIn> <Component {...props}/> </FadeIn> )}/> ) <FadingRoute path="/cool" component={Something}/>
TIPS: 第三坑! <Route component>
的优先级要比 <Route render>
高,所以不要在同一个 <Route>
中同时使用这两个属性。
和之前版本没太大区别,重点看下组件属性:
to(string/object):要跳转的路径或地址;
replace(bool): 为 true 时 ,点击链接后将使用新地址替换掉访问历史记录里面的原地址; 为 false 时 ,点击链接后将在原有访问历史记录的基础上添加一个新的纪录。 默认为 false ;
示例如下:
// Link组件示例 // to为string <Link to="/about">关于</Link> // to为obj <Link to={{ pathname: '/courses', search: '?sort=name', hash: '#the-hash', state: { fromDashboard: true } }}/> // replace <Link to="/courses" replace />
<NavLink>
是 <Link>
的一个特定版本, 会在匹配上当前 URL 的时候会给已经渲染的元素添加样式参数,组件属性:
activeClassName(string):设置选中样式,默认值为 active;
activeStyle(object):当元素被选中时, 为此元素添加样式;
exact(bool):为 true 时, 只有当地址完全匹配 class 和 style 才会应用;
strict(bool):为 true 时,在确定位置是否与当前 URL 匹配时,将考虑位置 pathname 后的斜线; isActive(func):判断链接是否激活的额外逻辑的功能;
从这里我们也可以看出,新版本的路由在组件化上面确实下了不少功夫,来看看NavLink的使用示例:
// activeClassName选中时样式为selected <NavLink to="/faq" activeClassName="selected" >FAQs</NavLink> // 选中时样式为activeStyle的样式设置 <NavLink to="/faq" activeStyle={{ fontWeight: 'bold', color: 'red' }} >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 to="/events/123" isActive={oddEvent} >Event 123</NavLink>
该组件用来渲染匹配地址的第一个 <Route>
或者 <Redirect>
。那么它与使用一堆route又有什么区别呢?
<Switch>
的独特之处是独它仅仅渲染一个路由。相反地,每一个包含匹配地址(location)的 <Route>
都会被渲染。思考下面的代码:
<Route path="/about" component={About}/> <Route path="/:user" component={User}/> <Route component={NoMatch}/>
如果现在的URL是 /about
,那么 <About>
, <User>
, 还有 <NoMatch>
都会被渲染,因为它们都与路径(path)匹配。这种设计,允许我们以多种方式将多个 <Route>
组合到我们的应用程序中,例如侧栏(sidebars),面包屑(breadcrumbs),bootstrap tabs等等。 然而,偶尔我们只想选择一个 <Route>
来渲染。如果我们现在处于 /about
,我们也不希望匹配 /:user
(或者显示我们的 “404” 页面 )。以下是使用 Switch 的方法来实现:
<Switch> <Route exact path="/" component={Home}/> <Route path="/about" component={About}/> <Route path="/:user" component={User}/> <Route component={NoMatch}/> </Switch>
现在,如果我们处于 /about
, <Switch>
将开始寻找匹配的 <Route>
。 <Route path="/about"/>
将被匹配, <Switch>
将停止寻找匹配并渲染 <About>
。同样,如果我们处于 /michael
, <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!

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



CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Apple rolled out the iOS 17.4 update on Tuesday, bringing a slew of new features and fixes to iPhones. The update includes new emojis, and EU users will also be able to download them from other app stores. In addition, the update also strengthens the control of iPhone security and introduces more "Stolen Device Protection" setting options to provide users with more choices and protection. "iOS17.3 introduces the "Stolen Device Protection" function for the first time, adding extra security to users' sensitive information. When the user is away from home and other familiar places, this function requires the user to enter biometric information for the first time, and after one hour You must enter information again to access and change certain data, such as changing your Apple ID password or turning off stolen device protection.

Xiaomi car software provides remote car control functions, allowing users to remotely control the vehicle through mobile phones or computers, such as opening and closing the vehicle's doors and windows, starting the engine, controlling the vehicle's air conditioner and audio, etc. The following is the use and content of this software, let's learn about it together . Comprehensive list of Xiaomi Auto app functions and usage methods 1. The Xiaomi Auto app was launched on the Apple AppStore on March 25, and can now be downloaded from the app store on Android phones; Car purchase: Learn about the core highlights and technical parameters of Xiaomi Auto, and make an appointment for a test drive. Configure and order your Xiaomi car, and support online processing of car pickup to-do items. 3. Community: Understand Xiaomi Auto brand information, exchange car experience, and share wonderful car life; 4. Car control: The mobile phone is the remote control, remote control, real-time security, easy

Chirp Down can also be called JJDown. This is a video download tool specially created for Bilibili. However, many friends do not understand this software. Today, let the editor explain to you what Chirp Down is? How to use chirp down. 1. The origin of Chirpdown Chirpdown originated in 2014. It is a very old video downloading software. The interface adopts Win10 tile style, which is simple, beautiful and easy to operate. Chirna is the poster girl of Chirpdown, and the artist is あさひクロイ. Jijidown has always been committed to providing users with the best download experience, constantly updating and optimizing the software, solving various problems and bugs, and adding new functions and features. The function of Chirp Down Chirp Down is
