欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

React Router v4 入坑指南(小结)

程序员文章站 2023-11-26 11:52:28
距离react router v4 正式发布也已经过去三个月了,这周把一个react的架子做了升级,之前的路由用的还是v2.7.0版的,所以决定把路由也升级下,正好“尝尝鲜...

距离react router v4 正式发布也已经过去三个月了,这周把一个react的架子做了升级,之前的路由用的还是v2.7.0版的,所以决定把路由也升级下,正好“尝尝鲜”...

江湖传言,目前官方同时维护 2.x 和 4.x 两个版本。(ヾ(。ꏿ﹏ꏿ)ノ゙咦,此刻相信机智如我的你也会发现,reactrouter v3 去哪儿了?整丢了??巴拉出锅了???敢不敢给我个完美的解释!?)事实上 3.x 版本相比于 2.x 并没有引入任何新的特性,只是将 2.x 版本中部分废弃 api 的 warning 移除掉而已。按照规划,没有历史包袱的新项目想要使用稳定版的 reactrouter 时,应该使用 reactrouter 3.x。目前 3.x 版本也还处于 beta 阶段,不过会先于 4.x 版本正式发布。如果你已经在使用 2.x 的版本,那么升级 3.x 将不会有任何额外的代码变动。

礼貌性简介下

React Router v4 入坑指南(小结)

react router v4 相较于前面三个版本有根本性变化,首先是遵循 just component 的 api 设计理念,其次api方面也精简了不少,对新手来说降低了学习难度,但如果是对之前项目的重构,嗯,简直无**可说。本次升级的主要特点如下:

  • 声明式(declarative)
  • 可组合 (composability)

react router v4 遵循了 react 的理念: 万物皆组件 。因此 升级之后的 route、link、switch等都是一个普通的组件。

react router v4 基于 lerna 管理多个 repository。在此代码库包括:

  1. react-router react router 核心
  2. react-router-dom 用于 dom 绑定的 react router
  3. react-router-native 用于 react native 的 react router
  4. react-router-redux react router 和 redux 的集成
  5. react-router-config 静态路由配置帮助助手

插件初引入

通常我们在 react 的使用中,一般要引入两个包, react 和  react-dom ,那么 react-routerreact-router-dom 是不是两个都要引用呢? 注意,前方高能,入门第一坑就在这里 。他们两个只要引用一个就行了,不同之处就是后者比前者多出了 <link> <browserrouter> 这样的 dom 类组件。因此我们只需引用 react-router-dom 这个包就ok了。当然,如果搭配 redux ,你还需要使用 react-router-redux

主要组件简介

在4.0之前版本的 api 中, <router> 组件的 children 只能是 react router 提供的各种组件,如 <route>、<indexroute>、<redirect> 等。而在 react router 4 中,你可以将各种组件及标签放进 <router> 组件中,他的角色也更像是 redux 中的 <provider> 。**不同的是 <provider> 是用来保持与 store 的更新,而 <router> 是用来保持与 location 的同步。**示例如下:

// 示例1
<router>
 <div>
  <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}/>
 </div>
 </router>

router是所有路由组件共用的底层接口,一般我们的应用并不会使用这个接口,而是使用高级的路由:

  1. <browserrouter> :使用 html5 提供的 history api 来保持 ui 和 url 的同步;
  2. <hashrouter> :使用 url 的 hash (例如:window.location.hash) 来保持 ui 和 url 的同步;
  3. <memoryrouter> :能在内存保存你 “url” 的历史纪录(并没有对地址栏读写);
  4. <nativerouter> :为使用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>

没错,示例2在没有 <div> 爸爸的保护下,会报如下异常信息:

React Router v4 入坑指南(小结)

我们知道,route组件主要的作用就是当一个location匹配路由的path时,渲染某些ui。示例如下:

<router>
 <div>
 <route exact path="/" component={home}/>
 <route path="/news" component={newsfeed}/>
 </div>
</router>

// 如果应用的地址是/,那么相应的ui会类似这个样子:
<div>
 <home/>
</div>

// 如果应用的地址是/news,那么相应的ui就会成为这个样子:
<div>
 <newsfeed/>
</div>

<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={() => <div>home</div>}/>

// 包装/合成
const fadingroute = ({ component: component, ...rest }) => (
 <route {...rest} render={props => (
 <fadein>
  <component {...props}/>
 </fadein>
 )}/>
)

<fadingroute path="/cool" component={something}/>

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: '/courses',
 search: '?sort=name',
 hash: '#the-hash',
 state: { fromdashboard: true }
}}/>

// replace 
<link to="/courses" replace />

<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: '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> 将被渲染。

以上就是我对react router v4 的初试,反正也是一边查文档,一边试水的,如有错误或疏漏,还请大家谅解并不吝指正!也希望大家多多支持。