真正学会 React 是一个漫长的过程。html
你会发现,它不是一个库,也不是一个框架,而是一个庞大的体系。想要发挥它的威力,整个技术栈都要配合它改造。你要学习一整套解决方案,从后端到前端,都是全新的作法。前端
举例来讲,React 不使用 HTML,而使用 JSX 。它打算抛弃 DOM,要求开发者不要使用任何 DOM 方法。它甚至还抛弃了 SQL ,本身发明了一套查询语言 GraphQL 。固然,这些你均可以不用,React 照样运行,可是就发挥不出它的最大威力。
这样说吧,你只要用了 React,就会发现合理的选择就是,采用它的整个技术栈。
本文介绍 React 体系的一个重要部分:路由库React-Router。它是官方维护的,事实上也是惟一可选的路由库。它经过管理 URL,实现组件的切换和状态的变化,开发复杂的应用几乎确定会用到。react
本文针对初学者,尽可能写得简洁易懂。预备知识是 React 的基本用法,能够参考我写的《React 入门实例教程》。
另外,我没有准备示例库,由于官方的示例库很是棒,由浅入深,分红14步,每一步都有详细的代码解释。我强烈建议你先跟着作一遍,而后再看下面的API讲解。
([说明] 本文写做时,React-router 是 2.x 版,本文的内容只适合这个版本,与最新的 4.x 版不兼容。目前,官方同时维护 2.x 和 4.x 两个版本,因此前者依然能够用在项目中。2017年3月)
1、基本用法
React Router 安装命令以下。webpack
$ npm install -S react-router
使用时,路由器Router就是React的一个组件。web
import { Router } from 'react-router';
render(<Router/>, document.getElementById('app'));
Router组件自己只是一个容器,真正的路由要经过Route组件定义。npm
import { Router, Route, hashHistory } from 'react-router';后端
render((
<Router history={hashHistory}>api
<Route path="/" component={App}/>
</Router>
), document.getElementById('app'));
上面代码中,用户访问根路由/(好比http://www.example.com/),组件APP就会加载到document.getElementById('app')。
你可能还注意到,Router组件有一个参数history,它的值hashHistory表示,路由的切换由URL的hash变化决定,即URL的#部分发生变化。举例来讲,用户访问http://www.example.com/,实际会看到的是http://www.example.com/#/。
Route组件定义了URL路径与组件的对应关系。你能够同时使用多个Route组件。浏览器
<Router history={hashHistory}>
<Route path="/" component={App}/>
<Route path="/repos" component={Repos}/>
<Route path="/about" component={About}/>
</Router>
上面代码中,用户访问/repos(好比http://localhost:8080/#/repos)时,加载Repos组件;访问/about(http://localhost:8080/#/about)时,加载About组件。
2、嵌套路由
Route组件还能够嵌套。服务器
<Router history={hashHistory}>
<Route path="/" component={App}>
<Route path="/repos" component={Repos}/> <Route path="/about" component={About}/>
</Route>
</Router>
上面代码中,用户访问/repos时,会先加载App组件,而后在它的内部再加载Repos组件。
<App>
<Repos/>
</App>
App组件要写成下面的样子。
export default React.createClass({
render() {
return <div> {this.props.children} </div>
}
})
上面代码中,App组件的this.props.children属性就是子组件。
子路由也能够不写在Router组件里面,单独传入Router组件的routes属性。
let routes = <Route path="/" component={App}>
<Route path="/repos" component={Repos}/>
<Route path="/about" component={About}/>
</Route>;
<Router routes={routes} history={browserHistory}/>
3、 path 属性
Route组件的path属性指定路由的匹配规则。这个属性是能够省略的,这样的话,无论路径是否匹配,老是会加载指定组件。
请看下面的例子。
<Route path="inbox" component={Inbox}>
<Route path="messages/:id" component={Message} />
</Route>
上面代码中,当用户访问/inbox/messages/:id时,会加载下面的组件。
<Inbox>
<Message/>
</Inbox>
若是省略外层Route的path参数,写成下面的样子。
<Route component={Inbox}>
<Route path="inbox/messages/:id" component={Message} />
</Route>
如今用户访问/inbox/messages/:id时,组件加载仍是原来的样子。
<Inbox>
<Message/>
</Inbox>
4、通配符
path属性可使用通配符。
<Route path="/hello/:name">
// 匹配 /hello/michael
// 匹配 /hello/ryan
<Route path="/hello(/:name)">
// 匹配 /hello
// 匹配 /hello/michael
// 匹配 /hello/ryan
<Route path="/files/.">
// 匹配 /files/hello.jpg
// 匹配 /files/hello.html
<Route path="/files/*">
// 匹配 /files/
// 匹配 /files/a
// 匹配 /files/a/b
<Route path="/*/.jpg">
// 匹配 /files/hello.jpg
// 匹配 /files/path/to/file.jpg
通配符的规则以下。
(1):paramName
:paramName匹配URL的一个部分,直到遇到下一个/、?、#为止。这个路径参数能够经过this.props.params.paramName取出。
(2)()
()表示URL的这个部分是可选的。
(3)*
*匹配任意字符,直到模式里面的下一个字符为止。匹配方式是非贪婪模式。
(4) **
** 匹配任意字符,直到下一个/、?、#为止。匹配方式是贪婪模式。
path属性也可使用相对路径(不以/开头),匹配时就会相对于父组件的路径,能够参考上一节的例子。嵌套路由若是想摆脱这个规则,可使用绝对路由。
路由匹配规则是从上到下执行,一旦发现匹配,就再也不其他的规则了。
<Route path="/comments" ... />
<Route path="/comments" ... />
上面代码中,路径/comments同时匹配两个规则,第二个规则不会生效。
设置路径参数时,须要特别当心这一点。
<Router>
<Route path="/:userName/:id" component={UserPage}/>
<Route path="/about/me" component={About}/>
</Router>
上面代码中,用户访问/about/me时,不会触发第二个路由规则,由于它会匹配/:userName/:id这个规则。所以,带参数的路径通常要写在路由规则的底部。
此外,URL的查询字符串/foo?bar=baz,能够用this.props.location.query.bar获取。
5、IndexRoute 组件
下面的例子,你会不会以为有一点问题?
<Router>
<Route path="/" component={App}>
<Route path="accounts" component={Accounts}/> <Route path="statements" component={Statements}/>
</Route>
</Router>
上面代码中,访问根路径/,不会加载任何子组件。也就是说,App组件的this.props.children,这时是undefined。
所以,一般会采用{this.props.children || <Home/>}这样的写法。这时,Home明明是Accounts和Statements的同级组件,却没有写在Route中。
IndexRoute就是解决这个问题,显式指定Home是根路由的子组件,即指定默认状况下加载的子组件。你能够把IndexRoute想象成某个路径的index.html。
<Router>
<Route path="/" component={App}>
<IndexRoute component={Home}/> <Route path="accounts" component={Accounts}/> <Route path="statements" component={Statements}/>
</Route>
</Router>
如今,用户访问/的时候,加载的组件结构以下。
<App>
<Home/>
</App>
这种组件结构就很清晰了:App只包含下级组件的共有元素,自己的展现内容则由Home组件定义。这样有利于代码分离,也有利于使用React Router提供的各类API。
注意,IndexRoute组件没有路径参数path。
6、Redirect 组件
<Redirect>组件用于路由的跳转,即用户访问一个路由,会自动跳转到另外一个路由。
<Route path="inbox" component={Inbox}>
{/ 从 /inbox/messages/:id 跳转到 /messages/:id /}
<Redirect from="messages/:id" to="/messages/:id" />
</Route>
如今访问/inbox/messages/5,会自动跳转到/messages/5。
7、IndexRedirect 组件
IndexRedirect组件用于访问根路由的时候,将用户重定向到某个子组件。
<Route path="/" component={App}>
<IndexRedirect to="/welcome" />
<Route path="welcome" component={Welcome} />
<Route path="about" component={About} />
</Route>
上面代码中,用户访问根路径时,将自动重定向到子组件welcome。
8、Link
Link组件用于取代元素,生成一个连接,容许用户点击后跳转到另外一个路由。它基本上就是元素的React 版本,能够接收Router的状态。
render() {
return <div>
<ul role="nav"> <li><Link to="/about">About</Link></li> <li><Link to="/repos">Repos</Link></li> </ul>
</div>
}
若是但愿当前的路由与其余路由有不一样样式,这时可使用Link组件的activeStyle属性。
<Link to="/about" activeStyle={{color: 'red'}}>About</Link>
<Link to="/repos" activeStyle={{color: 'red'}}>Repos</Link>
上面代码中,当前页面的连接会红色显示。
另外一种作法是,使用activeClassName指定当前路由的Class。
<Link to="/about" activeClassName="active">About</Link>
<Link to="/repos" activeClassName="active">Repos</Link>
上面代码中,当前页面的连接的class会包含active。
在Router组件以外,导航到路由页面,可使用浏览器的History API,像下面这样写。
import { browserHistory } from 'react-router';
browserHistory.push('/some/path');
9、IndexLink
若是连接到根路由/,不要使用Link组件,而要使用IndexLink组件。
这是由于对于根路由来讲,activeStyle和activeClassName会失效,或者说老是生效,由于/会匹配任何子路由。而IndexLink组件会使用路径的精确匹配。
<IndexLink to="/" activeClassName="active">
Home
</IndexLink>
上面代码中,根路由只会在精确匹配时,才具备activeClassName。
另外一种方法是使用Link组件的onlyActiveOnIndex属性,也能达到一样效果。
<Link to="/" activeClassName="active" onlyActiveOnIndex={true}>
Home
</Link>
实际上,IndexLink就是对Link组件的onlyActiveOnIndex属性的包装。
10、histroy 属性
Router组件的history属性,用来监听浏览器地址栏的变化,并将URL解析成一个地址对象,供 React Router 匹配。
history属性,一共能够设置三种值。
browserHistory
hashHistory
createMemoryHistory
若是设为hashHistory,路由将经过URL的hash部分(#)切换,URL的形式相似example.com/#/some/path。
import { hashHistory } from 'react-router'
render(
<Router history={hashHistory} routes={routes} />,
document.getElementById('app')
)
若是设为browserHistory,浏览器的路由就再也不经过Hash完成了,而显示正常的路径example.com/some/path,背后调用的是浏览器的History API。
import { browserHistory } from 'react-router'
render(
<Router history={browserHistory} routes={routes} />,
document.getElementById('app')
)
可是,这种状况须要对服务器改造。不然用户直接向服务器请求某个子路由,会显示网页找不到的404错误。
若是开发服务器使用的是webpack-dev-server,加上--history-api-fallback参数就能够了。
$ webpack-dev-server --inline --content-base . --history-api-fallback
createMemoryHistory主要用于服务器渲染。它建立一个内存中的history对象,不与浏览器URL互动。
const history = createMemoryHistory(location)
11、表单处理
Link组件用于正常的用户点击跳转,可是有时还须要表单跳转、点击按钮跳转等操做。这些状况怎么跟React Router对接呢?
下面是一个表单。
<form onSubmit={this.handleSubmit}>
<input type="text" placeholder="userName"/>
<input type="text" placeholder="repo"/>
<button type="submit">Go</button>
</form>
第一种方法是使用browserHistory.push
import { browserHistory } from 'react-router'
// ...
handleSubmit(event) {
event.preventDefault() const userName = event.target.elements[0].value const repo = event.target.elements[1].value const path = `/repos/${userName}/${repo}` browserHistory.push(path)
},
第二种方法是使用context对象。
export default React.createClass({
// ask for router
from context
contextTypes: {
router: React.PropTypes.object
},
handleSubmit(event) {
// ... this.context.router.push(path)
},
})
12、路由的钩子
每一个路由都有Enter和Leave钩子,用户进入或离开该路由时触发。
<Route path="about" component={About} />
<Route path="inbox" component={Inbox}>
<Redirect from="messages/:id" to="/messages/:id" />
</Route>
上面的代码中,若是用户离开/messages/:id,进入/about时,会依次触发如下的钩子。
/messages/:id的onLeave
/inbox的onLeave
/about的onEnter
下面是一个例子,使用onEnter钩子替代<Redirect>组件。
<Route path="inbox" component={Inbox}>
<Route
path="messages/:id" onEnter={ ({params}, replace) => replace(`/messages/${params.id}`) }
/>
</Route>
onEnter钩子还能够用来作认证。
const requireAuth = (nextState, replace) => {
if (!auth.isAdmin()) { // Redirect to Home page if not an Admin replace({ pathname: '/' }) }
}
export const AdminRoutes = () => {
return (
<Route path="/admin" component={Admin} onEnter={requireAuth} />
)
}
下面是一个高级应用,当用户离开一个路径的时候,跳出一个提示框,要求用户确认是否离开。
const Home = withRouter(
React.createClass({
componentDidMount() { this.props.router.setRouteLeaveHook( this.props.route, this.routerWillLeave ) }, routerWillLeave(nextLocation) { // 返回 false 会继续停留当前页面, // 不然,返回一个字符串,会显示给用户,让其本身决定 if (!this.state.isSaved) return '确认要离开?'; },
})
)
上面代码中,setRouteLeaveHook方法为Leave钩子指定routerWillLeave函数。该方法若是返回false,将阻止路由的切换,不然就返回一个字符串,提示用户决定是否要切换。
(完)