ReactRouter-V4 构建之道与源码分析

开发 开发工具
本文即是我在构建 React Router V4 过程中的考虑以及所谓路由即组件思想的落地实践。

[[188988]]

多年之后当我回想起初学客户端路由的那个下午,满脑子里充斥着的只是对于单页应用的惊叹与浆糊。彼时我还是将应用代码与路由代码当做两个独立的部分进行处理,就好像同父异母的兄弟尽管不喜欢对方但是不得不在一起。幸而这些年里我能够和其他优秀的开发者进行交流,了解他们对于客户端路由的看法。尽管他们中的大部分与我“英雄所见略同”,但是我还是找到了合适的平衡路由的抽象程度与复杂程度的方法。本文即是我在构建 React Router V4 过程中的考虑以及所谓路由即组件思想的落地实践。首先我们来看下我们在构建路由过程中的测试代码,你可以用它来测试你的自定义路由:

  1. const Home = () => ( 
  2.   <h2>Home</h2> 
  3.  
  4. const About = () => ( 
  5.   <h2>About</h2> 
  6.  
  7. const Topic = ({ topicId }) => ( 
  8.   <h3>{topicId}</h3> 
  9.  
  10. const Topics = ({ match }) => { 
  11.   const items = [ 
  12.     { name'Rendering with React', slug: 'rendering' }, 
  13.     { name'Components', slug: 'components' }, 
  14.     { name'Props v. State', slug: 'props-v-state' }, 
  15.   ] 
  16.  
  17.   return ( 
  18.     <div> 
  19.       <h2>Topics</h2> 
  20.       <ul> 
  21.         {items.map(({ name, slug }) => ( 
  22.           <li key={name}> 
  23.             <Link to={`${match.url}/${slug}`}>{name}</Link> 
  24.           </li> 
  25.         ))} 
  26.       </ul> 
  27.       {items.map(({ name, slug }) => ( 
  28.         <Route key={name} path={`${match.path}/${slug}`} render={() => ( 
  29.           <Topic topicId={name} /> 
  30.         )} /> 
  31.       ))} 
  32.       <Route exact path={match.url} render={() => ( 
  33.         <h3>Please select a topic.</h3> 
  34.       )}/> 
  35.     </div> 
  36.   ) 
  37.  
  38. const App = () => ( 
  39.   <div> 
  40.     <ul> 
  41.       <li><Link to="/">Home</Link></li> 
  42.       <li><Link to="/about">About</Link></li> 
  43.       <li><Link to="/topics">Topics</Link></li> 
  44.     </ul> 
  45.  
  46.     <hr/> 
  47.  
  48.     <Route exact path="/" component={Home}/> 
  49.     <Route path="/about" component={About}/> 
  50.     <Route path="/topics" component={Topics} /> 
  51.   </div> 

如果你对于 React Router v4 尚不是完全了解,我们先对上述代码中涉及到的相关关键字进行解释。Route 会在当前 URL 与 path 属性值相符的时候渲染相关组件,而 Link 提供了声明式的,易使用的方式来在应用内进行跳转。换言之,Link 组件允许你更新当前 URL,而 Route 组件则是根据 URL 渲染组件。本文并不专注于讲解 RRV4 的基础概念,你可以前往官方文档了解更多知识;本文是希望介绍我在构建 React Router V4 过程中的思维考虑过程,值得一提的是,我很欣赏 React Router V4 中的 Just Components 概念,这一点就不同于 React Router 之前的版本中将路由与组件隔离来看,而允许了路由组件像普通组件一样自由组合。相信对于 React 组件相当熟悉的开发者绝不会陌生于如何将路由组件嵌入到正常的应用中。

Route

我们首先来考量下如何构建Route组件,包括其暴露的 API,即 Props。在我们上面的示例中,我们会发现Route组件包含三个 Props:exact、path 以及 component。这也就意味着我们的propTypes声明如下:

  1. static propTypes = { 
  2.   exact: PropTypes.bool, 
  3.   path: PropTypes.string, 
  4.   component: PropTypes.func, 

这里有一些微妙的细节需要考虑,首先对于path并没有设置为必须参数,这是因为我们认为对于没有指定关联路径的Route组件应该自动默认渲染。而component参数也没有被设置为必须是因为我们提供了其他的方式进行渲染,譬如render函数:

  1. <Route path='/settings' render={({ match }) => { 
  2.   return <Settings authed={isAuthed} match={match} /> 
  3. }} /> 

render 函数允许你方便地使用内联函数来创建 UI 而不是创建新的组件,因此我们也需要将该函数设置为 propTypes:

  1. static propTypes = { 
  2.   exact: PropTypes.bool, 
  3.   path: PropTypes.string, 
  4.   component: PropTypes.func, 
  5.   render: PropTypes.func, 

在确定了 Route 需要接收的组件参数之后,我们需要来考量其实际功能;Route 核心的功能在于能够当 URL 与 path 属性相一致时执行渲染操作。基于这个论断,我们首先需要实现判断是否匹配的功能,如果判断为匹配则执行渲染否则返回空值。我们在这里将该函数命名为 matchPatch,那么此时整个 Route 组件的 render 函数定义如下:

  1. class Route extends Component { 
  2.   static propTypes = { 
  3.     exact: PropTypes.bool, 
  4.     path: PropTypes.string, 
  5.     component: PropTypes.func, 
  6.     render: PropTypes.func, 
  7.   } 
  8.  
  9.   render () { 
  10.     const { 
  11.       path, 
  12.       exact, 
  13.       component, 
  14.       render, 
  15.     } = this.props 
  16.  
  17.     const match = matchPath( 
  18.       location.pathname, // global DOM variable 
  19.       { path, exact } 
  20.     ) 
  21.  
  22.     if (!match) { 
  23.       // Do nothing because the current 
  24.       // location doesn't match the path prop. 
  25.  
  26.       return null 
  27.     } 
  28.  
  29.     if (component) { 
  30.       // The component prop takes precedent over the 
  31.       // render method. If the current location matches 
  32.       // the path prop, create a new element passing in 
  33.       // match as the prop. 
  34.  
  35.       return React.createElement(component, { match }) 
  36.     } 
  37.  
  38.     if (render) { 
  39.       // If there's a match but component 
  40.       // was undefined, invoke the render 
  41.       // prop passing in match as an argument. 
  42.  
  43.       return render({ match }) 
  44.     } 
  45.  
  46.     return null 
  47.   } 

现在的 Route 看起来已经相对明确了,当路径相匹配的时候才会执行界面渲染,否则返回为空。现在我们再回过头来考虑客户端路由中常见的跳转策略,一般来说用户只有两种方式会更新当前 URL。一种是用户点击了某个锚标签或者直接操作 history 对象的 replace/push 方法;另一种是用户点击前进/后退按钮。无论哪一种方式都要求我们的路由系统能够实时监听 URL 的变化,并且在 URL 发生变化时及时地做出响应,渲染出正确的页面。我们首先来考虑下如何处理用户点击前进/后退按钮。React Router 使用 History 的 .listen 方法来监听当前 URL 的变化,其本质上还是直接监听 HTML5 的 popstate 事件。popstate 事件会在用户点击某个前进/后退按钮的时候触发;而在每次重渲染的时候,每个 Route 组件都会重现检测当前 URL 是否匹配其预设的路径参数。

  1. class Route extends Component { 
  2.   static propTypes: { 
  3.     path: PropTypes.string, 
  4.     exact: PropTypes.bool, 
  5.     component: PropTypes.func, 
  6.     render: PropTypes.func, 
  7.   } 
  8.  
  9.   componentWillMount() { 
  10.     addEventListener("popstate", this.handlePop) 
  11.   } 
  12.  
  13.   componentWillUnmount() { 
  14.     removeEventListener("popstate", this.handlePop) 
  15.   } 
  16.  
  17.   handlePop = () => { 
  18.     this.forceUpdate() 
  19.   } 
  20.  
  21.   render() { 
  22.     const { 
  23.       path, 
  24.       exact, 
  25.       component, 
  26.       render, 
  27.     } = this.props 
  28.  
  29.     const match = matchPath(location.pathname, { path, exact }) 
  30.  
  31.     if (!match) 
  32.       return null 
  33.  
  34.     if (component) 
  35.       return React.createElement(component, { match }) 
  36.  
  37.     if (render) 
  38.       return render({ match }) 
  39.  
  40.     return null 
  41.   } 

你会发现上面的代码与之前的相比多了挂载与卸载 popstate 监听器的功能,其会在组件挂载时添加一个 popstate 监听器;当监听到 popstate 事件被触发时,我们会调用 forceUpdate 函数来强制进行重渲染。总结而言,无论我们在系统中设置了多少的路由组件,它们都会独立地监听 popstate 事件并且相应地执行重渲染操作。接下来我们继续讨论 matchPath 这个 Route 组件中至关重要的函数,它负责决定当前路由组件的 path 参数是否与当前 URL 相一致。这里还必须提下我们设置的另一个 Route 的参数 exact,其用于指明路径匹配策略;当 exact 值被设置为 true 时,仅当路径完全匹配于 location.pathname 才会被认为匹配成功:

pathlocation.pathnameexactmatches?/one/one/twotrueno/one/one/twofalseyes

让我们深度了解下 matchPath 函数的工作原理,该函数的签名如下:

  1. const match = matchPath(location.pathname, { path, exact }) 

其中函数的返回值 match 应该根据路径是否匹配的情况返回为空或者一个对象。基于这些推导我们可以得出 matchPatch 的原型:

  1. const matchPath = (pathname, options) => { 
  2.   const { exact = false, path } = options 

这里我们使用 ES6 的解构赋值,当某个属性未定义时我们使用预定义地默认值,即 false。我在上文提及的 path 非必要参数的具体支撑实现就在这里,我们首先进行空检测,当发现 path 为未定义或者为空时则直接返回匹配成功:

  1. const matchPath = (pathname, options) => { 
  2.   const { exact = false, path } = options 
  3.  
  4.   if (!path) { 
  5.     return { 
  6.       path: null
  7.       url: pathname, 
  8.       isExact: true
  9.     } 
  10.   } 

接下来继续考虑具体执行匹配的部分,React Router 使用了 pathToRegex 来检测是否匹配,即可以用简单的正则表达式:

  1. const matchPath = (pathname, options) => { 
  2.   const { exact = false, path } = options 
  3.  
  4.   if (!path) { 
  5.     return { 
  6.       path: null
  7.       url: pathname, 
  8.       isExact: true
  9.     } 
  10.   } 
  11.  
  12.   const match = new RegExp(`^${path}`).exec(pathname) 
  13.  

这里使用的 .exec 函数,会在包含指定的文本时返回一个数组,否则返回空值;下表即是当我们的路由设置为 /topics/components时具体的返回:

  1. | path                    | location.pathname    | return value             | 
  2. ----------------------- | -------------------- | ------------------------ | 
  3. | `/`                     | `/topics/components` | `['/']`                  | 
  4. | `/about`                | `/topics/components` | `null`                   | 
  5. | `/topics`               | `/topics/components` | `['/topics']`            | 
  6. | `/topics/rendering`     | `/topics/components` | `null`                   | 
  7. | `/topics/components`    | `/topics/components` | `['/topics/components']` | 
  8. | `/topics/props-v-state` | `/topics/components` | `null`                   | 
  9. | `/topics`               | `/topics/components` | `['/topics']`            | 

这里大家就会看出来,我们会为每个 <Route> 实例创建一个 match 对象。在获取到 match 对象之后,我们需要再做如下判断是否匹配:

  1. const matchPath = (pathname, options) => { 
  2.   const { exact = false, path } = options 
  3.  
  4.   if (!path) { 
  5.     return { 
  6.       path: null
  7.       url: pathname, 
  8.       isExact: true
  9.     } 
  10.   } 
  11.  
  12.   const match = new RegExp(`^${path}`).exec(pathname) 
  13.  
  14.   if (!match) { 
  15.     // There wasn't a match. 
  16.     return null 
  17.   } 
  18.  
  19.   const url = match[0] 
  20.   const isExact = pathname === url 
  21.  
  22.   if (exact && !isExact) { 
  23.     // There was a match, but it wasn't 
  24.     // an exact match as specified by 
  25.     // the exact prop. 
  26.  
  27.     return null 
  28.   } 
  29.  
  30.   return { 
  31.     path, 
  32.     url, 
  33.     isExact, 
  34.   } 

Link

上文我们已经提及通过监听 popstate 状态来响应用户点击前进/后退事件,现在我们来考虑通过构建 Link 组件来处理用户通过点击锚标签进行跳转的事件。Link 组件的 API 应该如下所示:

  1. <Link to='/some-path' replace={false} /> 

其中的 to 是一个指向跳转目标地址的字符串,而 replace 则是布尔变量来指定当用户点击跳转时是替换 history 栈中的记录还是插入新的记录。基于上述的 API 设计,我们可以得到如下的组件声明:

  1. class Link extends Component { 
  2.   static propTypes = { 
  3.     to: PropTypes.string.isRequired, 
  4.     replace: PropTypes.bool, 
  5.   } 

现在我们已经知道 Link 组件的渲染函数中需要返回一个锚标签,不过我们的前提是要避免每次用户切换路由的时候都进行整页的刷新,因此我们需要为每个锚标签添加一个点击事件的处理器:

  1. class Link extends Component { 
  2.   static propTypes = { 
  3.     to: PropTypes.string.isRequired, 
  4.     replace: PropTypes.bool, 
  5.   } 
  6.  
  7.   handleClick = (event) => { 
  8.     const { replaceto } = this.props 
  9.     event.preventDefault() 
  10.  
  11.     // route here. 
  12.   } 
  13.  
  14.   render() { 
  15.     const { to, children} = this.props 
  16.  
  17.     return ( 
  18.       <a href={to} onClick={this.handleClick}> 
  19.         {children} 
  20.       </a> 
  21.     ) 
  22.   } 

这里实际的跳转操作我们还是执行 History 中的抽象的 push 与 replace 函数,在使用 browserHistory 的情况下我们本质上还是使用 HTML5 中的 pushState 与 replaceState 函数。pushState 与 replaceState 函数都要求输入三个参数,首先是一个与***的历史记录相关的对象,在 React Router 中我们并不需要该对象,因此直接传入一个空对象;第二个参数是标题参数,我们同样不需要改变该值,因此直接传入空即可;***第三个参数则是我们需要的,用于指明新的相对地址的字符串:

  1. const historyPush = (path) => { 
  2.   history.pushState({}, null, path) 
  3.  
  4. const historyReplace = (path) => { 
  5.   history.replaceState({}, null, path) 

而后在 Link 组件内,我们会根据 replace 参数来调用 historyPush 或者 historyReplace 函数:

  1. class Link extends Component { 
  2.   static propTypes = { 
  3.     to: PropTypes.string.isRequired, 
  4.     replace: PropTypes.bool, 
  5.   } 
  6.   handleClick = (event) => { 
  7.     const { replaceto } = this.props 
  8.     event.preventDefault() 
  9.  
  10.     replace ? historyReplace(to) : historyPush(to
  11.   } 
  12.  
  13.   render() { 
  14.     const { to, children} = this.props 
  15.  
  16.     return ( 
  17.       <a href={to} onClick={this.handleClick}> 
  18.         {children} 
  19.       </a> 
  20.     ) 
  21.   } 

组件注册

现在我们需要考虑如何保证用户点击了 Link 组件之后触发全部路由组件的检测与重渲染。在我们上面实现的 Link 组件中,用户执行跳转之后浏览器的显示地址会发生变化,但是页面尚不能重新渲染;我们声明的 Route 组件并不能收到相应的通知。为了解决这个问题,我们需要追踪那些显现在界面上实际被渲染的 Route 组件并且当路由变化时调用它们的 forceUpdate 方法。React Router 主要通过有机组合 setState、context 以及 history.listen 方法来实现该功能。每个 Route 组件被挂载时我们会将其加入到某个数组中,然后当位置变化时,我们可以遍历该数组然后对每个实例调用 forceUpdate 方法:

  1. let instances = [] 
  2.  
  3. const register = (comp) => instances.push(comp) 
  4. const unregister = (comp) => instances.splice(instances.indexOf(comp), 1) 

这里我们创建了两个函数,当 Route 挂载时调用 register 函数,而卸载时调用 unregister 函数。然后无论何时调用 historyPush 或者 historyReplace 函数时都会遍历实例数组中的对象的渲染方法,此时我们的 Route 组件就需要声明为如下样式:

  1. class Route extends Component { 
  2.   static propTypes: { 
  3.     path: PropTypes.string, 
  4.     exact: PropTypes.bool, 
  5.     component: PropTypes.func, 
  6.     render: PropTypes.func, 
  7.   } 
  8.  
  9.   componentWillMount() { 
  10.     addEventListener("popstate", this.handlePop) 
  11.     register(this) 
  12.   } 
  13.  
  14.   componentWillUnmount() { 
  15.     unregister(this) 
  16.     removeEventListener("popstate", this.handlePop) 
  17.   } 
  18.  
  19.   ... 

然后我们需要更新 historyPush 与 historyReplace 函数:

  1. const historyPush = (path) => { 
  2.   history.pushState({}, null, path) 
  3.   instances.forEach(instance => instance.forceUpdate()) 
  4.  
  5. const historyReplace = (path) => { 
  6.   history.replaceState({}, null, path) 
  7.   instances.forEach(instance => instance.forceUpdate()) 

这样的话就保证了无论何时用户点击 <Link> 组件之后,在位置显示变化的同时,所有的 <Route> 组件都能够被通知到并且执行重匹配与重渲染。现在我们完整的路由解决方案就成形了:

  1. import React, { PropTypes, Component } from 'react' 
  2.  
  3. let instances = [] 
  4.  
  5. const register = (comp) => instances.push(comp) 
  6. const unregister = (comp) => instances.splice(instances.indexOf(comp), 1) 
  7.  
  8. const historyPush = (path) => { 
  9.   history.pushState({}, null, path) 
  10.   instances.forEach(instance => instance.forceUpdate()) 
  11.  
  12. const historyReplace = (path) => { 
  13.   history.replaceState({}, null, path) 
  14.   instances.forEach(instance => instance.forceUpdate()) 
  15.  
  16. const matchPath = (pathname, options) => { 
  17.   const { exact = false, path } = options 
  18.  
  19.   if (!path) { 
  20.     return { 
  21.       path: null
  22.       url: pathname, 
  23.       isExact: true 
  24.     } 
  25.   } 
  26.  
  27.   const match = new RegExp(`^${path}`).exec(pathname) 
  28.  
  29.   if (!match) 
  30.     return null 
  31.  
  32.   const url = match[0] 
  33.   const isExact = pathname === url 
  34.  
  35.   if (exact && !isExact) 
  36.     return null 
  37.  
  38.   return { 
  39.     path, 
  40.     url, 
  41.     isExact, 
  42.   } 
  43.  
  44. class Route extends Component { 
  45.   static propTypes: { 
  46.     path: PropTypes.string, 
  47.     exact: PropTypes.bool, 
  48.     component: PropTypes.func, 
  49.     render: PropTypes.func, 
  50.   } 
  51.  
  52.   componentWillMount() { 
  53.     addEventListener("popstate", this.handlePop) 
  54.     register(this) 
  55.   } 
  56.  
  57.   componentWillUnmount() { 
  58.     unregister(this) 
  59.     removeEventListener("popstate", this.handlePop) 
  60.   } 
  61.  
  62.   handlePop = () => { 
  63.     this.forceUpdate() 
  64.   } 
  65.  
  66.   render() { 
  67.     const { 
  68.       path, 
  69.       exact, 
  70.       component, 
  71.       render, 
  72.     } = this.props 
  73.  
  74.     const match = matchPath(location.pathname, { path, exact }) 
  75.  
  76.     if (!match) 
  77.       return null 
  78.  
  79.     if (component) 
  80.       return React.createElement(component, { match }) 
  81.  
  82.     if (render) 
  83.       return render({ match }) 
  84.  
  85.     return null 
  86.   } 
  87.  
  88. class Link extends Component { 
  89.   static propTypes = { 
  90.     to: PropTypes.string.isRequired, 
  91.     replace: PropTypes.bool, 
  92.   } 
  93.   handleClick = (event) => { 
  94.     const { replaceto } = this.props 
  95.  
  96.     event.preventDefault() 
  97.     replace ? historyReplace(to) : historyPush(to
  98.   } 
  99.  
  100.   render() { 
  101.     const { to, children} = this.props 
  102.  
  103.     return ( 
  104.       <a href={to} onClick={this.handleClick}> 
  105.         {children} 
  106.       </a> 
  107.     ) 
  108.   } 

另外,React Router API 中提供了所谓 <Redirect> 组件,允许执行路由跳转操作:

  1. class Redirect extends Component { 
  2.   static defaultProps = { 
  3.     push: false 
  4.   } 
  5.  
  6.   static propTypes = { 
  7.     to: PropTypes.string.isRequired, 
  8.     push: PropTypes.bool.isRequired, 
  9.   } 
  10.  
  11.   componentDidMount() { 
  12.     const { to, push } = this.props 
  13.  
  14.     push ? historyPush(to) : historyReplace(to
  15.   } 
  16.  
  17.   render() { 
  18.     return null 
  19.   } 

注意这个组件并没有真实地进行界面渲染,而是仅仅进行了简单的跳转操作。到这里本文也就告一段落了,希望能够帮助你去了解 React Router V4 的设计思想以及 Just Component 的接口理念。我一直说 React 会让你成为更加优秀地开发者,而 React Router 则会是你不小的助力。

【本文是51CTO专栏作者“张梓雄 ”的原创文章,如需转载请通过51CTO与作者联系】

戳这里,看该作者更多好文

责任编辑:武晓燕 来源: 51CTO专栏
相关推荐

2021-02-16 10:55:02

Nodejs模块

2016-10-21 13:03:18

androidhandlerlooper

2021-09-08 10:47:33

Flink执行流程

2016-11-29 09:38:06

Flume架构核心组件

2016-11-25 13:26:50

Flume架构源码

2016-11-25 13:14:50

Flume架构源码

2020-06-04 12:15:08

Pythonkafka代码

2009-12-22 13:36:39

Linux Sysfs

2021-08-06 15:06:09

腾讯开源Apache

2013-06-26 10:25:39

2009-11-30 17:33:07

微软

2016-11-29 16:59:46

Flume架构源码

2022-04-05 12:59:07

源码线程onEvent

2021-10-27 11:29:49

Linux框架内核

2011-03-15 11:33:18

iptables

2014-08-26 11:11:57

AsyncHttpCl源码分析

2017-10-25 13:20:43

软件安全模型

2011-06-08 09:22:54

Samba

2009-09-28 10:49:13

ITIL摩卡

2021-03-15 18:47:25

日志开发源码
点赞
收藏

51CTO技术栈公众号