概要

开发单页应用, 首先绕不开的内容就是路由, react router v4 版本是最新的版本. 和之前的版本相比, 成熟了很多, 也简单了很多, 使用起来更加方便.

核心 component

react-router V4 可以用于 Web 和 Native. 这里主要讨论基于 Web 的应用.

react-router 有很多 Components, 但是只要掌握下面 3 个 Component 就可以管理好 react 应用的路由了.

Router component

Router 是整个应用的路由. 在 Web 应用中, 使用 BrowerRouter 来包装 App

<BrowserRouter>
<App />
</BrowserRouter>

然后, 在 App component 中, 就可以使用 Route 来定义各个路由对应的 component

Route component

每个 Route 都是一个具体的路由, 对应一个具体的页面. Route 可以对应一个 Component, 也可以直接写个匿名的 render 函数.

Route 中最常用的属性就是 path, 也就是路由的地址, 除此之外, Route 最重要的作用是会将 { match, location, history } 3 个属性注入到对应的 Component 或者 render 函数中.

Link component

Link 是用来导航的, 也就是在不同 Route 之间切换就会用到 Link.

常用路由示例

示例工程

示例工程的创建采用 create-react-app 工具.

$ create-react-app route-test
$ cd route-test
$ yarn add react-router-dom

基本使用

修改工程中的 App.js 文件, 增加 route 的 sample

import React, { Component } from 'react'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import './App.css' const Index = () => <h2>Home</h2>
const About = () => <h2>About</h2>
const Users = () => <h2>Users</h2> class App extends Component {
render() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about/">About</Link>
</li>
<li>
<Link to="/users/">Users</Link>
</li>
</ul>
</nav> <Route path="/" exact component={Index} />
<Route path="/about/" component={About} />
<Route path="/users/" component={Users} />
</div>
</Router>
)
}
} export default App

这个示例中, 就包含了 3 个常用组件 Router, Route 和 Link

路由参数

路由的参数可以加在 path 上, 下面的示例中, Users Component 可以通过注入的 match 来得到 URL 中的参数.

import React, { Component } from 'react'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import './App.css' const Index = () => <h2>Home</h2>
const About = () => <h2>About</h2>
const Users = ({ match }) => (
<h2>
User is {match.params.name}, age: {match.params.age}
</h2>
) class App extends Component {
render() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about/">About</Link>
</li>
<li>
<Link to="/users/test/16">Users</Link>
</li>
</ul>
</nav> <Route path="/" exact component={Index} />
<Route path="/about/" component={About} />
<Route path="/users/:name/:age" component={Users} />
</div>
</Router>
)
}
} export default App

query 参数

除了上面那种 RESTful 的参数方式, 也可以通过 query 来传递参数. 下例中, 通过 location.search 来获取 querystring, 至于解析 querystring, 已有很多现成的方法可以使用.

import React, { Component } from 'react'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import './App.css' const Index = () => <h2>Home</h2>
const About = ({ match, location }) => (
<h2>About's search string: {location.search}</h2>
)
const Users = ({ match }) => (
<h2>
User is {match.params.name}, age: {match.params.age}
</h2>
) class App extends Component {
render() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to={{ pathname: '/about/', search: '?name=test&age=16' }}>
About
</Link>
</li>
<li>
<Link to="/users/test/16">Users</Link>
</li>
</ul>
</nav> <Route path="/" exact component={Index} />
<Route path="/about/" component={About} />
<Route path="/users/:name/:age" component={Users} />
</div>
</Router>
)
}
} export default App

FAQ

在刚开始使用 react-router 时, 可能会有些疑问, 我整理了自己在使用中一些疑惑:

match 是如何注入到 Component 中的

match, location, history 这 3 个 object, 是由 Route Component 作为 props 注入到它的 render 方法, 或者 component={xxx} prop 对应的组件中的

match.path 和 match.url 有什么区别

  • match.path 是用来做匹配用的, 也就是在 Route 中使用的
  • match.url 是用来迁移页面用的, 也就是在 Link 中使用的

比如上面的例子中, 对于 /users

  • match.path 是 users:name/:age
  • match.url 是 /users/test/16

BrowserRouter 和 HashRouter 有什么区别

  • BrowserRouter 是用于和 Server 有交互的 Router
  • HashRouter 是用于静态文件服务的 Router

Route 和 Switch 的区别

当有多个 Route 并列时, 如果外层没有包裹 Switch, 那么匹配到的 Route 都会被 render, 如果有 Switch, 那么只会 render 第一个匹配上的 Route

Route 如果不设置 path, 则每次都会匹配成功

Link 和 NavLink 的区别

NavLink 是一种特殊的 Link, 它可以设置一些 active 时的样式.

路由信息和 redux 状态管理如何结合

路由信息本质上也是一种状态信息, 放不放在 redux 中来管理, 相信很多人都会纠结. 官方的建议是不要把路由的状态放在 redux 的 store 中来管理, 理由如下:

  1. 路由状态一般只有 Components 才关心, 不管放不放在 redux 中, Component 的代码不会有什么改变
  2. 大部分情况下, 路由跳转都是通过 Link, NavLink, Redirct 来完成, 如果需要通过代码, 或者异步 action 中来跳转, 可以通过传入 history 对象来完成.
  3. 路由变化一般不需要通过时间旅行(time travel, redux 的一个调试工具)来 debug.

react-router(v4)的更多相关文章

  1. [Web 前端] React Router v4 入坑指南

    cp from : https://www.jianshu.com/p/6a45e2dfc9d9 万恶的根源 距离React Router v4 正式发布也已经过去三个月了,这周把一个React的架子 ...

  2. React Router V4发布

    React Router V4 正式版发布,该版本相较于前面三个版本有根本性变化,遵循 Just Component 的 API 设计理念. 本次升级的主要变更有: 声明式 Declarative 可 ...

  3. [React Router v4] Intercept Route Changes

    If a user has entered some input, or the current Route is in a “dirty” state and we want to confirm ...

  4. [React Router v4] Redirect to Another Page

    Overriding a browser's current location without breaking the back button or causing an infinite redi ...

  5. [React Router v4] Render Multiple Components for the Same Route

    React Router v4 allows us to render Routes as components wherever we like in our components. This ca ...

  6. [React Router v4] Conditionally Render a Route with the Switch Component

    We often want to render a Route conditionally within our application. In React Router v4, the Route ...

  7. [React Router v4] Render Catch-All Routes with the Switch Component

    There are many cases where we will need a catch-all route in our web applications. This can include ...

  8. [React Router v4] Render Nested Routes

    With React Router v4 the entire library is built as a series of React components. That means that cr ...

  9. [React Router v4] Parse Query Parameters

    React Router v4 ignores query parameters entirely. That means that it is up to you to parse them so ...

  10. [React Router v4] Use Regular Expressions with Routes

    We can use regular expressions to more precisely define the paths to our routes in React Router v4. ...

随机推荐

  1. 关于mui前端传值,springboot后台接收值的问题

    最近做app,使用mui的ajax给后台传参,后台一直接收不到值,表示很蛋疼.这里通过网上搜索加上个人实践,总结归纳了三种前端传值和后台接收的方式. 第一种: 前端: data: JSON.strin ...

  2. 20170319 - pycurl 提示 libcurl link-time version is older than compile-time version

    使用 conda update anaconda 升级后,运行程序得到如下提示: ImportError: pycurl: libcurl link-time version (7.45.0) is ...

  3. 数据库 【redis】 命令大全

    以下纯属搬砖,我用Python抓取的redis命令列表页内容 如果想看命令的具体使用可查去官网查看,以下整理为个人查找方便而已 地理位置GEOADD 将指定的地理空间位置(纬度.经度.名称)添加到指定 ...

  4. 史上最全的springboot导出pdf文件

    最近项目有一个导出报表文件的需求,我脑中闪过第一念头就是导出pdf(产品经理没有硬性规定导出excel还是pdf文件),于是赶紧上网查看相关的资料,直到踩了无数的坑把功能做出来了才知道其实导出exce ...

  5. [.net core] 在 Windows 中运行出现 WinHttpException: The parameter is incorrect

    有一个 web 服务一直跑在 docker 中,今天需要在 Windows 上部署一个备份版本,于是,签出源代码,编译,运行.结果抛出 500 ,日志中有如下记录: System.Net.Http.H ...

  6. 【安富莱TCPnet网络教程】HTTP通信实例

    第41章      HTTP超文本传输协议基础知识 本章节为大家讲解HTTP(HyperText Transfer Protocol,超文本传输协议),从本章节开始,正式进入嵌入式Web的设计和学习. ...

  7. ubuntu 16.04安装perf

    ljc@ubuntu:~$ perf 程序“perf”尚未安装. 您可以使用以下命令安装: sudo apt install linux-tools-common ljc@ubuntu:~$ sudo ...

  8. 和逛微博、刷朋友圈一样玩转 GitHub

    自打毕业之后,可以说每天打开 Github 或Email 看有没有 watch 项目的消息或者自己项目的 issue,然后在Explore 看看社区内项目的走势,紧接着开始写代码搬砖的工作,偶尔也会关 ...

  9. ASP.NET Core Web API 集成测试

    本文需要您了解ASP.NET Core Web API 和 xUnit的相关知识. 这里有xUnit的介绍: https://www.cnblogs.com/cgzl/p/9178672.html#t ...

  10. 【Python3爬虫】百度一下,坑死你?

    一.写在前面 这个标题是借用的路人甲大佬的一篇文章的标题(百度一下,坑死你),而且这次的爬虫也是看了这篇文章后才写出来的,感兴趣的可以先看下这篇文章. 前段时间有篇文章<搜索引擎百度已死> ...