React Router 运用教程(阮一峰)

真正学会 React 是一个冗长的历程。

你会发明,它不是一个库,也不是一个框架,而是一个巨大的系统。想要发挥它的威力,全部手艺栈都要合营它革新。你要进修一整套处置惩罚方案,从后端到前端,都是全新的做法。

举例来讲,React 不运用 HTML,而运用 JSX 。它盘算扬弃 DOM,要求开辟者不要运用任何 DOM 要领。它以至还扬弃了 SQL ,自身发清楚明了一套查询言语 GraphQL 。固然,这些你都能够不必,React 照样运转,然则就发挥不出它的最大威力。
如许说吧,你只需用了 React,就会发明合理的挑选就是,采纳它的全部手艺栈。
本文引见 React 系统的一个重要部份:路由库React-Router。它是官方保护的,事实上也是唯一可选的路由库。它经由过程治理 URL,完成组件的切换和状况的变化,开辟庞杂的运用险些肯定会用到。

本文针对初学者,只管写得简约易懂。准备学问是 React 的基础用法,能够参考我写的《React 入门实例教程》。
别的,我没有准备示例库,由于官方的示例库异常棒,由浅入深,分红14步,每一步都有细致的代码诠释。我强烈建议你先随着做一遍,然后再看下面的API解说。
([申明] 本文写作时,React-router 是 2.x 版,本文的内容只合适这个版本,与最新的 4.x 版不兼容。如今,官方同时保护 2.x 和 4.x 两个版本,所以前者依旧能够用在项目中。2017年3月)
一、基础用法
React Router 装置敕令以下。

$ npm install -S react-router
运用时,路由器Router就是React的一个组件。

import { Router } from ‘react-router’;
render(<Router/>, document.getElementById(‘app’));
Router组件自身只是一个容器,真正的路由要经由过程Route组件定义。

import { Router, Route, hashHistory } from ‘react-router’;

render((
<Router history={hashHistory}>

<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组件。
二、嵌套路由
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}/>
三、 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>
四、通配符
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猎取。
五、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。
六、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。
七、IndexRedirect 组件
IndexRedirect组件用于接见根路由的时刻,将用户重定向到某个子组件。

<Route path=”/” component={App}>
<IndexRedirect to=”/welcome” />
<Route path=”welcome” component={Welcome} />
<Route path=”about” component={About} />
</Route>
上面代码中,用户接见根途径时,将自动重定向到子组件welcome。
八、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’);
九、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属性的包装。
十、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)
十一、表单处置惩罚
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)

},
})
十二、路由的钩子
每一个路由都有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,将阻挠路由的切换,不然就返回一个字符串,提醒用户决议是不是要切换。
(完)

原文链接:http://www.ruanyifeng.com/blo…

    原文作者:Mr_Fu
    原文地址: https://segmentfault.com/a/1190000009677823
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞