基本路由配置
<Router>
<Route path="/" component={App}>
<Route path="about" component={About} />
<Route path="inbox" component={Inbox}>
<Route path="messages/:id" component={Message} />
</Route>
</Route>
</Router>
即
URL | 组件 |
---|---|
/ | App |
/about | App -> About |
/inbox | App -> Inbox |
/inbox/messages/:id | App -> Inbox -> Messages |
路由匹配原理
路由拥有三个属性来决定是否“匹配“一个 URL:
- 嵌套关系 和
- 它的 路径语法
- 它的 优先级
嵌套关系
当一个给定的 URL 被调用时,整个集合中(命中的部分)都会被渲染。嵌套路由被描述成一种树形结构。React Router 会深度优先遍历整个路由配置来寻找一个与给定的 URL 相匹配的路由。
路径语法
路由路径是匹配一个(或一部分)URL 的 一个字符串模式。大部分的路由路径都可以直接按照字面量理解,除了以下几个特殊的符号:
- :paramName – 匹配一段位于 /、? 或 # 之后的 URL。 命中的部分将被作为一个参数
- () – 在它内部的内容被认为是可选的
- 匹配任意字符(非贪婪的)直到命中下一个字符或者整个 URL 的末尾,并创建一个 splat 参数
优先级
最后,路由算法会根据定义的顺序自顶向下匹配路由。因此,当你拥有两个兄弟路由节点配置时,你必须确认前一个路由不会匹配后一个路由中的路径。
默认路由(IndexRoute)与 IndexLink
默认路由(IndexRoute)
<Router>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="accounts" component={Accounts}/>
<Route path="statements" component={Statements}/>
</Route>
</Router>
通过IndexRoute
来设置默认路由,即使 Home 作为最高层级的路由出现.
跳转前确认
React Router 提供一个 routerWillLeave 生命周期钩子,这使得 React 组件可以拦截正在发生的跳转,或在离开 route 前提示用户
routerWillLeave
返回值有以下两种
- return false 取消此次跳转
- return 返回提示信息,在离开 route 前提示用户进行确认。
可以在 route 组件 中引入 Lifecycle mixin 来安装这个钩子
import { Lifecycle } from 'react-router'
const Home = React.createClass({
// 假设 Home 是一个 route 组件,它可能会使用
// Lifecycle mixin 去获得一个 routerWillLeave 方法。
mixins: [ Lifecycle ],
routerWillLeave(nextLocation) {
if (!this.state.isSaved)
return 'Your work is not saved! Are you sure you want to leave?'
},
// ...
})
路由生命周期
1. 当用户打开应用的 ‘/’ 页面
组件 | 生命周期 |
---|---|
App | componentDidMount |
Home | componentDidMount |
Invoice | N/A |
Account | N/A |
2. 当用户从 ‘/’ 跳转到 '/invoice/123’
组件 | 生命周期 |
---|---|
App | componentWillReceiveProps , componentDidUpdate |
Home | componentWillUnmount |
Invoice | componentDidMount |
Account | N/A |
- App 从 router 中接收到新的 props(例如 children、params、location 等数据), 所以 App 触发了 componentWillReceiveProps 和 componentDidUpdate 两个生命周期方法
- Home 不再被渲染,所以它将被移除
- Invoice 首次被挂载
3. 当用户从 /invoice/123 跳转到 /invoice/789
组件 | 生命周期 |
---|---|
App | componentWillReceiveProps , componentDidUpdate |
Home | N/A |
Invoice | componentWillReceiveProps ,componentDidUpdate |
Account | N/A |
所有的组件之前都已经被挂载, 所以只是从 router 更新了 props.
4. 当从 /invoice/789 跳转到 /accounts/123
组件 | 生命周期 |
---|---|
App | componentWillReceiveProps , componentDidUpdate |
Home | N/A |
Invoice | componentWillUnmount |
Account | componentDidMount |