React Router v4 Getting Started Guide
This article mainly introduces the React Router v4 entry guide (summary). The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.
It has been three months since React Router v4 was officially released. This week, a React shelf was upgraded. The previous routing was still using version v2.7.0. , so I decided to upgrade the routing as well, just to "try something new"...
Rumors in the world are that the official currently maintains two versions of 2.x and 4.x at the same time. (ヾ(。ꏿ﹏ꏿ)ノ゙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 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
<Route>, , 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. **Examples are 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 URL hash (for example: window.location.hash) to keep the UI and URL synchronized;
< MemoryRouter>
: Can save the history of your "URL" in memory (without reading and writing the address bar);
- ##
: Provides routing support for using React Native;
## - : Never changes the address;
TIPS : This is the second pitfall. Unlike the previous Router, only one child element is allowed under the
The negative example is here:
<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>
我们知道,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>
将被渲染。
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
The above is the detailed content of React Router v4 Getting Started Guide. 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

AI Hentai Generator
Generate AI Hentai for free.

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

With the launch of Windows 11, Microsoft has introduced some new features and updates, including a security feature called VBS (Virtualization-basedSecurity). VBS utilizes virtualization technology to protect the operating system and sensitive data, thereby improving system security. However, for some users, VBS is not a necessary feature and may even affect system performance. Therefore, this article will introduce how to turn off VBS in Windows 11 to help

VSCode Setup in Chinese: A Complete Guide In software development, Visual Studio Code (VSCode for short) is a commonly used integrated development environment. For developers who use Chinese, setting VSCode to the Chinese interface can improve work efficiency. This article will provide you with a complete guide, detailing how to set VSCode to a Chinese interface and providing specific code examples. Step 1: Download and install the language pack. After opening VSCode, click on the left

With the continuous development of technology, Linux operating systems have been widely used in various fields. Installing Deepin Linux system on tablets allows us to experience the charm of Linux more conveniently. Let’s discuss the installation of Deepin Linux on tablets. Specific steps for Linux. Preparation work Before installing Deepin Linux on the tablet, we need to make some preparations. We need to back up important data in the tablet to avoid data loss during the installation process. We need to download the image file of Deepin Linux and write it to to a USB flash drive or SD card for use during the installation process. Next, we can start the installation process. We need to set the tablet to start from the U disk or SD

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

Conda Usage Guide: Easily upgrade the Python version, specific code examples are required Introduction: During the development process of Python, we often need to upgrade the Python version to obtain new features or fix known bugs. However, manually upgrading the Python version can be troublesome, especially when our projects and dependent packages are relatively complex. Fortunately, Conda, as an excellent package manager and environment management tool, can help us easily upgrade the Python version. This article will introduce how to use

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

PHP7 Installation Directory Configuration Guide PHP is a popular server-side scripting language used to develop dynamic web pages. Currently, the latest version of PHP is PHP7, which introduces many new features and performance optimizations and is the preferred version for many websites and applications. When installing PHP7, it is very important to correctly configure the installation directory. This article will provide you with a detailed guide to configuring the PHP7 installation directory, with specific code examples. To download PHP7 first, you need to download it from the PHP official website (https://www.
