若是你已是一个正在开发中的react应用,想要引入更好的管理路由功能。那么,react-router是你最好的选择~
react-router版本现今已经到4.0.0了,而上一个稳定版本仍是2.8.1。相信我,若是你的项目中已经在使用react-router以前的版本,那必定要慎重的更新,由于新的版本是一次很是大的改动,若是你要更新,工做量并不小。
这篇文章不讨论版本的变化,只是讨论一下React-router4.0的用法和源码。
源码在这里:https://github.com/ReactTraining/react-routerjavascript
只须要在你的react app中引入一个包
yarn add react-router-dom@next
注:react-router-dom是对react-router的做了一些小升级的库,代码基于react-routerhtml
咱们直接上例子:html5
import React from 'react' import {BrowserRouter as Router,Route,Link} from 'react-router-dom' const Basic = () => ( <Router> <div> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/page1">Page1</Link></li> <li><Link to="/page2">Page2</Link></li> </ul> <hr/> <Route exact path="/" component={Home}/> <Route path="/page1" component={Page1}/> <Route path="/page2" component={Page2}/> </div> </Router> )
跟以前的版本同样,Router这个组件仍是一个容器,可是它的角色变了,4.0的Router下面能够听任意标签了,这意味着使用方式的转变,它更像redux中的provider了。经过上面的例子相信你也能够看到具体的变化。而真正的路由经过Route来定义。Link标签目前看来也没什么变化,依然能够理解为a标签,点击会改变浏览器Url的hash值,经过Route标签来捕获这个url并返回component属性中定义的组件,你可能注意到在为"/"写的路由中有一个exact关键字,这个关键字是将"/"作惟一匹配,不然"/"和"/xxx"都会匹配到path为"/"的路由,制定exact后,"/page1"就不会再匹配到"/"了。若是你不懂,动手试一下~java
经过Route路由的组件,能够拿到一个match参数,这个参数是一个对象,其中包含几个数据:node
咱们来实现一下刚才的Page2组件:react
const Page2 = ({ match }) => ( <div> <h2>Page2</h2> <ul> <li> <Link to={`${match.url}/branch1`}> branch1 </Link> </li> <li> <Link to={`${match.url}/branch2`}> branch2 </Link> </li> <li> <Link to={`${match.url}/branch3`}> branch3 </Link> </li> </ul> <Route path={`${match.url}/:branchId`} component={Branch} /> <Route exact path={match.url} render={() => ( <h3>Default Information</h3> )} /> </div> ) const Branch = ({ match }) => { console.log(match); return ( <div> <h3>{match.params.branchId}</h3> </div> ) }
很简单,动手试一试。须要注意的就只有Route的path中冒号":"后的部分至关于通配符,而匹配到的url将会把匹配的部分做为match.param中的属性传递给组件,属性名就是冒号后的字符串。git
细心的朋友确定注意到了上面的例子中我import的Router是BrowserRouter,这是什么东西呢?若是你用过老版本的react-router,你必定知道history。history是用来兼容不一样浏览器或者环境下的历史记录管理的,当我跳转或者点击浏览器的后退按钮时,history就必须记录这些变化,而以前的react-router将history分为三类。github
4.0以前版本的react-router针对三者分别实现了createHashHistory、createBrowserHistory和create MemoryHistory三个方法来建立三种状况下的history,这里就不讨论他们不一样的处理方式了,好奇的能够去了解一下~
到了4.0版本,在react-router-dom中直接将这三种history做了内置,因而咱们看到了BrowserRouter、HashRouter、MemoryRouter这三种Router,固然,你依然可使用React-router中的Router,而后本身经过createHistory来建立history来传入。web
react-router的history库依然使用的是 https://github.com/ReactTraining/history正则表达式
在例子中你可能注意到了Route的几个prop
他们都不是必填项,注意,若是path没有赋值,那么此Route就是默认渲染的。
Route的做用就是当url和Route中path属性的值匹配时,就渲染component中的组件或者render中的内容。
固然,Route其实还有几个属性,好比location,strict,chilren 但愿大家本身去了解一下。
说到这,那么Route的内部是怎样实现这个机制的呢?不难猜想确定是用一个匹配的方法来实现的,那么Route是怎么知道url更新了而后进行从新匹配并渲染的呢?
整理一下思路,在一个web 应用中,改变url无非是2种方式,一种是利用超连接进行跳转,另外一种是使用浏览器的前进和回退功能。前者的在触发Link的跳转事件以后触发,然后者呢?Route利用的是咱们上面说到过的history的listen方法来监听url的变化。为了防止引入新的库,Route的创做者选择了使用html5中的popState事件,只要点击了浏览器的前进或者后退按钮,这个事件就会触发,咱们来看一下Route的代码:
class Route extends Component { static propTypes: { path: PropTypes.string, exact: PropTypes.bool, component: PropTypes.func, render: PropTypes.func, } componentWillMount() { addEventListener("popstate", this.handlePop) } componentWillUnmount() { removeEventListener("popstate", this.handlePop) } handlePop = () => { this.forceUpdate() } render() { const { path, exact, component, render, } = this.props //location是一个全局变量 const match = matchPath(location.pathname, { path, exact }) return ( //有趣的是从这里咱们能够看出各属性渲染的优先级,component第一 component ? ( match ? React.createElement(component, props) : null ) : render ? ( // render prop is next, only called if there's a match match ? render(props) : null ) : children ? ( // children come last, always called typeof children === 'function' ? ( children(props) ) : !Array.isArray(children) || children.length ? ( // Preact defaults to empty children array React.Children.only(children) ) : ( null ) ) : ( null ) ) } }
这里我只贴出了关键代码,若是你使用过React,相信你能看懂,Route在组件将要Mount的时候添加popState事件的监听,每当popState事件触发,就使用forceUpdate强制刷新,从而基于当前的location.pathname进行一次匹配,再根据结果渲染。
PS:如今最新的代码中,Route源码实际上是经过componentWillReceiveProps中setState来实现从新渲染的,match属性是做为Route组件的state存在的.
那么这个关键的matchPath方法是怎么实现的呢?
Route引入了一个外部library:path-to-regexp。这个pathToRegexp方法用于返回一个知足要求的正则表达式,举个例子:
let keys = [],keys2=[] let re = pathToRegexp('/foo/:bar', keys) //re = /^\/foo\/([^\/]+?)\/?$/i keys = [{ name: 'bar', prefix: '/', delimiter: '/', optional: false, repeat: false, pattern: '[^\\/]+?' }] let re2 = pathToRegexp('/foo/bar', keys2) //re2 = /^\/foo\/bar(?:\/(?=$))?$/i keys2 = []
关于它的详细信息你能够看这里:https://github.com/pillarjs/path-to-regexp
值得一提的是matchPath方法中对匹配结果做了缓存,若是是已经匹配过的字符串,就不用再进行一次pathToRegexp了。
随后的代码就清晰了:
const match = re.exec(pathname) if (!match) return null const [ url, ...values ] = match const isExact = pathname === url //若是exact为true,须要pathname===url if (exact && !isExact) return null return { path, url: path === '/' && url === '' ? '/' : url, isExact, params: keys.reduce((memo, key, index) => { memo[key.name] = values[index] return memo }, {}) }
还记得上面说到的改变url的两种方式吗,咱们来讲说另外一种,Link,看一下它的参数:
static propTypes = { onClick: PropTypes.func, target: PropTypes.string, replace: PropTypes.bool, to: PropTypes.oneOfType([ PropTypes.string, PropTypes.object ]).isRequired }
onClick就不说了,target属性就是a标签的target属性,to至关于href。
而replace的意思跳转的连接是否覆盖history中当前的url,若为true,新的url将会覆盖history中的当前值,而不是向其中添加一个新的。
handleClick = (event) => { if (this.props.onClick) this.props.onClick(event) if ( !event.defaultPrevented && // 是否阻止了默认事件 event.button === 0 && // 肯定是鼠标左键点击 !this.props.target && // 避免打开新窗口的状况 !isModifiedEvent(event) // 无视特殊的key值,是否同时按下了ctrl、shift、alt、meta ) { event.preventDefault() const { history } = this.context.router const { replace, to } = this.props if (replace) { history.replace(to) } else { history.push(to) } } }
须要注意的是,history.push和history.replace使用的是pushState方法和replaceState方法。
我想单独再多说一下Redirect组件,源码颇有意思:
class Redirect extends React.Component { //...省略一部分代码 isStatic() { return this.context.router && this.context.router.staticContext } componentWillMount() { if (this.isStatic()) this.perform() } componentDidMount() { if (!this.isStatic()) this.perform() } perform() { const { history } = this.context.router const { push, to } = this.props if (push) { history.push(to) } else { history.replace(to) } } render() { return null } }
很容易注意到这个组件并无UI,render方法return了一个null。很容易产生这样一个疑问,既然没有UI为何react-router的创造者依然选择将Redirect写成一个组件呢?
我想咱们能够从做者口中的"Just Components API"中窥得缘由吧。
但愿这篇文章能够帮助你更好的建立你的React应用.