Home > Web Front-end > JS Tutorial > Case analysis using React Router v4 (with code)

Case analysis using React Router v4 (with code)

php中世界最好的语言
Release: 2018-06-09 16:02:45
Original
1410 people have browsed it

This time I will bring you a case analysis of using React Router v4 (with code). What are the precautions for using case analysis of React Router v4? The following is a practical case, let's take a look.

It has been three months since React Router v4 was officially released. This week I upgraded a React shelf. The previous routing was still using version v2.7.0, so I decided to upgrade the routing as well. , just "try something new"...

Rumors in the world are that the official currently maintains two versions, 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

React Router V4 follows the React philosophy:

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:

  1. react-router React Router core

  2. react-router-dom React Router for DOM binding

  3. react-router-native React Router for React Native

  4. react-router-redux Integration of React Router and Redux

  5. 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

<Router> component can only be the various components provided by React Router. Various components, such as <Route>, , <Redirect>, 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>
Copy after login
Router is the underlying interface shared by all routing components. Generally, our applications will not use this interface, but use advanced routing:

  1. : Use the history API provided by HTML5 to keep the UI and URL synchronized;

  2. : Use the hash of the URL (for example: window.location.hash) to keep the UI and URL in sync;

  3. : Can save your " URL" history (does not read or write the address bar);

  4. ##

    : Provide routing support for using React Native;

  5. <StaticRouter> :从不会改变地址;

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>
Copy after login

没错,示例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>
Copy after login

<Route> 组件有如下属性:

  1. path(string): 路由匹配路径。(没有path属性的Route 总是会 匹配);

  2. exact(bool):为true时,则要求路径与location.pathname必须完全匹配;

  3. 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> 提供了三种渲染内容的方法:

  1. <Route component> :在地址匹配的时候React的组件才会被渲染,route props也会随着一起被渲染;

  2. <Route render> :这种方式对于内联渲染和包装组件却不引起意料之外的重新挂载特别方便;

  3. <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}/>
Copy after login

TIPS: 第三坑! <Route component> 的优先级要比 <Route render> 高,所以不要在同一个 <Route> 中同时使用这两个属性。

和之前版本没太大区别,重点看下组件属性:

  1. to(string/object):要跳转的路径或地址;

  2. replace(bool): 为 true 时 ,点击链接后将使用新地址替换掉访问历史记录里面的原地址; 为 false 时 ,点击链接后将在原有访问历史记录的基础上添加一个新的纪录。 默认为 false

示例如下:

// Link组件示例
// to为string
<Link to="/about">关于</Link>
// to为obj
<Link to={{
 pathname: &#39;/courses&#39;,
 search: &#39;?sort=name&#39;,
 hash: &#39;#the-hash&#39;,
 state: { fromDashboard: true }
}}/>
// replace 
<Link to="/courses" replace />
Copy after login

<NavLink><Link> 的一个特定版本, 会在匹配上当前 URL 的时候会给已经渲染的元素添加样式参数,组件属性:

  1. activeClassName(string):设置选中样式,默认值为 active;

  2. activeStyle(object):当元素被选中时, 为此元素添加样式;

  3. exact(bool):为 true 时, 只有当地址完全匹配 class 和 style 才会应用;

  4. strict(bool):为 true 时,在确定位置是否与当前 URL 匹配时,将考虑位置 pathname 后的斜线; isActive(func):判断链接是否激活的额外逻辑的功能;

从这里我们也可以看出,新版本的路由在组件化上面确实下了不少功夫,来看看NavLink的使用示例:

// activeClassName选中时样式为selected
<NavLink
 to="/faq"
 activeClassName="selected"
>FAQs</NavLink>
// 选中时样式为activeStyle的样式设置
<NavLink
 to="/faq"
 activeStyle={{
 fontWeight: &#39;bold&#39;,
 color: &#39;red&#39;
 }}
>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>
Copy after login

该组件用来渲染匹配地址的第一个 <Route> 或者 <Redirect> 。那么它与使用一堆route又有什么区别呢?

<Switch> 的独特之处是独它仅仅渲染一个路由。相反地,每一个包含匹配地址(location)的 <Route> 都会被渲染。思考下面的代码:

<Route path="/about" component={About}/>
<Route path="/:user" component={User}/>
<Route component={NoMatch}/>
Copy after login

如果现在的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>
Copy after login

现在,如果我们处于 /about<Switch> 将开始寻找匹配的 <Route><Route path="/about"/> 将被匹配, <Switch> 将停止寻找匹配并渲染 <About> 。同样,如果我们处于 /michael<User> 将被渲染。

<p>相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

<p>推荐阅读:

<p>正则中句号使用范畴有哪些

<p>JS使用createElement()动态添加HTML

The above is the detailed content of Case analysis using React Router v4 (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template