React-Router v4
- 1. 设计理念
- 1.1. 动态路由
- 1.2. 嵌套路由
- 1.3. 响应式路由
- 2. 快速入门
- 2.1.
- 2.1.1. basename: string
- 2.2.
- 2.2.1. to: string || object
- 2.2.2. replace: bool
- 2.3.
- 2.3.1. component
- 2.3.2. render: func
- 2.3.3. children: func
- 2.3.4. path: string
- 2.3.5. exact: bool
- 2.4. history
- 2.5. location
- 2.6. match
- 2.1.
- 3. API 查漏补缺
- 3.1.
- 3.1.1. to: string || object
- 3.1.2. push: bool
- 3.1.3. from: string
- 3.2.
- 3.2.1. location: object
- 3.2.2. children: node
- 3.3.
- activeClassName: string
- activeStyle: object
- isActive: func
- 3.1.
1. 设计理念
React-Router v4 的核心思想是 “动态路由”,它是相对于 “静态路由” 提出的设计概念。
何为静态路由?在服务器端所有的路由都是在设计过程已经规划完成。在许多客户端框架中也遵循了上述思路,即在页面渲染之前先规划好路由,将路由导入到顶层的模块中。但这种理念在 React-Router 中不再适用,作者希望在学习 React-Router 之前放弃 “静态路由” 设计思路。
1.1. 动态路由
在 React-Router 中的所有设置都是组件,因此路由是随着应用的渲染被同时计算得到,而不是独立于应用之外。为了解释这个理念我们首先学习 React-Router 在应用中的使用,
-
将 React-Router 的组件声明到应用顶层:
import { BrowserRouter } from 'react-router-dom' ReactDOM.render((
-
使用 link 组件指向相应的位置:
const App = () => (
-
最后利用 Route 组件关联位置与显示 UI:
const App = () => (
如果用户访问 /dashboard
, Route 组件会将路由形式的对象 {match, location, history}
作为属性参数传给
组件进行渲染,否则不会渲染。
到此为止,似乎与 “静态路由” 的概念没有区别,但是不要忘记 Route 是一个组件,这就意味着 Route 组件是否渲染和其中的 path
和 component
都可以由父组件的状态或属性进行设置。
1.2. 嵌套路由
在动态路由中配置嵌套路由就好像 div 标签中嵌套一个 div , 因为 Route 就是一个组件标签。
const App = () => (
{/* 这里是 div 标签*/}
{/* 这里是 Route 组件标签*/}
)
// 当 url 匹配 /tacos 时, 该组件被渲染
const Tacos = ({ match }) => (
// 这是嵌套的 div 标签
{/* 这是嵌套的 Route 组件标签,
match.url 用以实现相对路径 */}
)
1.3. 响应式路由
利用动态路由理念很容易在 React-Native 中实现响应式的布局。
const App = () => (
)
const Invoices = () => (
{/* always show the nav */}
{screenIsSmall => screenIsSmall
// small screen has no redirect
?
// large screen does!
:
}
)
2. 快速入门
首先给出官方的基础案例:
import React from 'react'
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
// 三个基础呈现组件
const Home = () => (
Home
)
const About = () => (
About
)
const Topic = ({ match }) => (
{match.params.topicId}
)
// 一个内嵌的组件
const Topics = ({ match }) => (
Topics
-
Rendering with React
-
Components
-
Props v. State
(
Please select a topic.
)}/>
)
// 首页组件
const BasicExample = () => (
- Home
- About
- Topics
)
export default BasicExample
随后分析上例给出的三个 React-Router 组件,分别是
,
, 。
2.1.
这是一个路由管理器,使用 HTML5 的 history API (pushState
, replaceState
, popState
) 同步访问 URL 和组件。具体声明如下:
import { BrowserRouter } from 'react-router-dom'
2.1.1. basename: string
应用的根目录,如果你的应用只是整个服务中的子服务,仅适应于某个子目录,那么就应该设置这个参数。
// renders
2.2.
该组件用以声明应用的链接(导航)
import { Link } from 'react-router-dom'
About
2.2.1. to: string || object
定义需要导航的路径。
2.2.2. replace: bool
如果该选项设置为 true
,当你点击链接时,会在 history 栈中取代当前的状态路径而不是添加一个新状态路径。
2.3.
这是 React-Router 中最重要的组件了,当请求的状态路径与该组件给出的 path
一致时,会渲染所对应的 UI 组件。
import { BrowserRouter as Router, Route } from 'react-router-dom'
在
每一种方式都会传入相同形式的路由属性 —— {match, location, history}
。
2.3.1. component
使用 component 渲染方式时,React 会自动将所对应的组件转化为 React 组件,因此如果所对应组件是内联函数形式,请使用 render 或 children 渲染方式,避免每次都生成新的 React 组件。
2.3.2. render: func
该方式取代了React 生成组件的过程,而是直接执行一个函数,此外还经常用于路由的打包。
// 直接执行函数
Home}/>
// 打包路由
const FadingRoute = ({ component: Component, ...rest }) => (
(
)}/>
)
2.3.3. children: func
有时无论路径是否匹配都要渲染组件,这种情况下使用 children 渲染方式,它和 render 方式类似只是多了一个匹配过程。
const ListItemLink = ({ to, ...rest }) => (
(
)}/>
)
注意: component 和 render 方式都优先于 children 方式,因此无法在一个
组件中同时使用。
2.3.4. path: string
一个符合正则的有效 URL 路径,当 Route 中没有 path
时,该路由总是匹配 。
2.3.5. exact: bool
完全匹配的选项。
完全匹配的逻辑:
path | location.pathname | exact | matches? |
---|---|---|---|
/one | /one/two | true | no |
/one | /one/two | false | yes |
2.4. history
与
组件相关的还有三个对象,分别是 history
,match
, location
。在这节中我们先来了解 history
这个可变对象。
history 是 React-Router 极少的依赖模块之一,它主要作用是在不同的环境下管理会话。经常会使用到的 history 有:
-
browser history
:DOM 的具体应用,支持 HTML5 的 history API。 -
hash history
:DOM 的具体应用,用以兼容老版本的浏览器。 -
memory history
:在无 DOM 或测试环境下通过内存方式处理来实施,适合 React-Native。
和history 对象相关的主要属性和方法有:
-
length
:history 栈中的状态路径个数。 -
action
:当前的操作,字符串形式(PUSH, REPLACE, POP) -
location
:当前的状态路径。-
pathname
: URL 路径字段 -
search
:URL 查询字段 -
hash
:URL 的 hash 字段 -
state
:路径的状态,只在 browser 和 memory history 中有效。
-
-
push(path, [state])
:将状态路径压入 history 栈。 -
replace(path, [state])
:替换当前的状态路径。 -
go(n)
:向前移动当前指针 n 次。 -
goBack()
:go(-1)
-
goForward()
:go(1)
-
block(prompt)
:暂时阻止导航(“您确定离开”)。
history 是可变的,因此状态路径的访问方式推荐使用
的属性(props)里间接获取,而不是直接使用 history.location
。这可以保证在 React 生存周期里能够获得正确的比较。
class Comp extends React.Component {
componentWillReceiveProps(nextProps) {
// 返回 true
const locationChanged = nextProps.location !== this.props.location
// 错误,总是 false,因为 history 是可变的。
const locationChanged = nextProps.history.location !== this.props.history.location
}
}
2.5. location
在本文中我一直称之为状态路径,意思很明显就是具有状态的路径。该对象的与 url 对应,其具体属性如下:
{
key: 'ac3df4', // not with HashHistory!
pathname: '/somewhere'
search: '?some=search-string',
hash: '#howdy',
state: {
[userDefined]: true
}
}
状态路径会在以下几个位置由 React-Router 给出:
- Route component 由 this.props.location 给出
- Route render 由
({location}) => ()
给出 - Route children 由
({location}) => ()
给出 - withRouter 由 this.props.location 给出
你也可以在这几个位置定义状态路径:
- Link to
- Redirect to
- history.push
- history.replace
状态路径中的状态可用于 UI 分支的显示等情景。你也可以通过
和
组件传递状态路径,这在动画显示和延迟导航中非常有用。
2.6. match
match 对象用以描述
匹配 URL 的结果,其实就是
组件的 state ,
组件根据 match 对象进行状态转换,主要的属性有:
-
params
:键值对对象对应正则模式中的参数字段。 -
isExact
:是否完全匹配。 -
path
:匹配使用的正则模式。 -
url
:所匹配的 URL 路径字段。
可以在下面位置访问该对象,意味着将
的 state 传递为子组件的 props:
- Route component 由 this.props.match 给出
- Route render 由 ({match}) => () 给出
- Route children 由 ({match}) => () 给出
- withRouter 由 this.props.match 给出
如果路由中没有 path
,将匹配所有路径, match 对象就是其父对象的 match。
3. API 查漏补缺
官方教程中给出了许多实例,如果了解了上述 API 大部分代码都能看懂,还有一些 API 主要是增强使用的,为程序员在编程中提供了更多选择和便利。
3.1.
执行
将会使应用导航到一个新的位置,同时在 history 栈中新位置替换当前位置。因为是替换操作所以在
中通常会使用状态路径,并在状态路径中记录当前位置,以实现回溯路径的操作。
import { Route, Redirect } from 'react-router'
(
loggedIn ? (
) : (
)
)}/>
3.1.1. to: string || object
重定向的位置。
3.1.2. push: bool
该属性为 true 时,history 栈的操作不再是替换操作而是压入新的位置元素。
3.1.3. from: string
表明从那个位置进行重定向操作的。该属性只有在
组件中才有效。实际上该属性就是
组件中 path
属性的别称,与此同理还可以使用 exact
, strict
, path
。
3.2.
组件和语法中的 switch
功能类似,执行第一个匹配的路由。这个逻辑很直观也就是排他性,主要解决使用多个
时多个路由同时匹配的问题。
如果 URL 是 /about
,那么上述三个路由都匹配,此时希望只有第一个路由渲染,就需要使用
组件了:
import { Switch, Route } from 'react-router'
3.2.1. location: object
如果
组件中给出了 location 属性,子元素将不再与当前位置或 URL 进行匹配操作,而是与该属性进行匹配,并且匹配的子元素的 location 值将被覆盖为
的 location 属性值。
3.2.2. children: node
在
组件中子元素可以是
和
组件,
使用 path
属性进行匹配,而
使用 from
属性进行匹配。
3.3.
特殊的 组件,主要作用是实现导航栏。
activeClassName: string
当链接激活时的类名,默认是 active
。
activeStyle: object
链接激活时的样式。
FAQs
isActive: func
在链接匹配的基础上添加逻辑以决定是否该链接激活。
// only consider an event active if its event id is an odd number
const oddEvent = (match, location) => {
if (!match) {
return false
}
const eventID = parseInt(match.params.eventID)
return !isNaN(eventID) && eventID % 2 === 1
}
Event 123
其他属性 exact
, strict
, location
参考 。