react-router 学习笔记

react中的路由管理


总结

  1. 使用Router作为最外层的组件,每一层通过Routes进行配置,组件内容使用component特性匹配,路径使用path

  2. 嵌套的写法:把Routes写在Routes之中,在对应的组件内部使用this.props.children指代嵌套的Routes的子组件的component的代码

  3. 使用browserHistory和–browser-api-fallback配置

    • Route上指定的component组件会传入上一层的props,包括history, params, location等

    • 要位页面指定子页面(主要用于tab切换等),可以使用 ‘ : ‘冒号指定配置参数=> path: /path/:id

      • 页面在设置了参数param之后,可以不跳转到对应路径,而是根据参数进行页面内容的展示或是根据param进行一系列操作

笔记

1. rendering a route 构建路由

外层路由配置
1
2
3
4
5
<Router history={hashHistory}>
<Route path="/" component={App}/>
<Route path="/about" component={About}/>
<Route path="/repos" component={Repos}/>
</Router>

在router内嵌套不同页面的route即可

2. Nested routes 简单的嵌套

单页应用配置(使用this.props.children)
1
2
3
4
5
6
<Router history={hashHistory}>
<Route path="/" component={Nav}>
<Route path="/about" component={About}/>
<Route path="/repos" component={Repos}/>
</Route>
</Router>

设置一个单独的导航Nav,导航的切换使得框架内的内容发生变化

1
2
3
// Nav.js
//添加下列代码,表示嵌套在其后的子组件
{this.props.children}

多层嵌套

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<Router history={hashHistory}>
<Route path="/" component={App}>
<Route path="/about" component={About}/>
<Route path="/repos" component={Repos}>
<Route path="/repos/:userName/:repoName" component={RepoChild}/>
</Route>
</Route>
</Router>
//子组件
export default React.createClass({
render() {
return (
<div>
<p>Repos!</p>
<ul>
<li>
<Link to="/repos/reactjs/react-router">React Router</Link>
</li>
<li>
<Link to="/repos/facebook/react">React</Link>
</li>
</ul>
{this.props.children || "nothing here"}
</div>
)
}
})

3. params 参数

使用url的params
在Path中使用“:”作为参数的前缀

4. 根目录下的页面渲染

为path为”/“的route设置component即可
要注意设置this.props.children

  • 固定首页

    1
    import { IndexRoute } from "react-route"
  • 首页链接

    1
    2
    import { IndexLink } form "react-route"
    <Link onlyActiveOnIndex={true}/>

5. 使用browerHistory进行设置

需要在webpack中配置 –history-api-fallback