极客教程-前端开发让前端飞Web前端之路

学习React-router 4.x版本

2017-10-20  本文已影响384人  cbw100

这几天闲下来想开发我个人网站的极客教程的移动web版本,然后发现之前弄的开发移动web的环境过于老旧,于是重新弄了个结合现在最新的相关库的环境,相关文章可以看搭建我的网站的mobile版的开发环境

这不,刚弄好开发环境,准备大显身手一番,然而一来就碰壁了,卡在react-router路由这里,怎么都报错,搞了一会,都怀疑人生了。然后我就猜测是react-router的版本问题,果不其然,默认安装的新版本跟以前的用法稍微有点不一样的;我安装的版本是 4.2.0版本的。接下来,就是学习一下新的react-router写法及特性

1. 准备

需要在你的react app中安装:

npm install react-router
npm install react-router-dom

如果你没有相关react app 可以参照搭建我的网站的mobile版的开发环境,就是用create-react-app 快速搭建一个开发环境。

2. 使用

直接上例子吧,如果你是用create-react-app搭建的环境,就直接复制下面的代码运行吧,运行效果就出来了。

//好了接下来我们直接路由
//打开demo文件下的src文件夹,直接修改 App.js 

import React from 'react'
import {BrowserRouter as Router,Route,Link} from 'react-router-dom'//导入的方式跟之前有点变化

const One = () => (
    <div>
        <h2>首页</h2>
    </div>
)

const Two = () => (
    <div>
        <h2>我是第二页</h2>
    </div>
)

const Lists = ({ match }) => (
    <div>
        <h3>{match.params.ListsId}</h3>
    </div>
)

const List = ({ match }) => (
    <div>
        <h2>我是一个列表</h2>
        <ul>
            <li>
                <Link to={`${match.url}/我是第一个哈哈`}>
                    列表下边的第一个
                </Link>
            </li>
            <li>
                <Link to={`${match.url}/我是第二个呵呵`}>
                    列表下边的第二个
                </Link>
            </li>
            <li>
                <Link to={`${match.url}/我是第三个嘿嘿`}>
                    列表下边的第三个
                </Link>
            </li>
        </ul>
        <Route path={`${match.url}/:ListsId`} component={Lists}/>
        <Route exact path={match.url} render={() => (
            <h3>点击上边的列表项此处显示与url地址一样的...</h3>
        )}/>
    </div>
)

const RouterList = () => (
    <Router>
        <div>
            <Link to="/">首页</Link>
            <br/>
            <Link to="/two">第二页</Link>
            <br/>
            <Link to="/Lists">一个列表</Link>
            <br/>
            <Route exact path="/" component={One}/>
            <Route path="/two" component={Two}/>
            <Route path="/Lists" component={List}/>
        </div>
    </Router>
)
export default RouterList

跟之前的版本一样,Router这个组件还是一个容器,但是它的角色变了,4.x的Router下面可以放任意标签了,这意味着使用方式的转变,它更像redux中的provider了。通过上面的例子相信你也可以看到具体的变化。而真正的路由通过Route来定义。Link标签目前看来也没什么变化,依然可以理解为a标签,点击会改变浏览器Url的hash值,通过Route标签来捕获这个url并返回component属性中定义的组件,你可能注意到在为"/"写的路由中有一个exact关键字,这个关键字是将"/"做唯一匹配,否则"/"和"/xxx"都会匹配到path为"/"的路由,制定exact后,"/"就不会再匹配到"/xxx"了。如果你不懂,动手试一下~

通过Route路由的组件,可以拿到一个match参数,这个参数是一个对象,其中包含几个数据:

3. Router标签

细心的朋友肯定注意到了上面的例子中我import的Router是BrowserRouter,这是什么东西呢?如果你用过老版本的react-router,你一定知道history。history是用来兼容不同浏览器或者环境下的历史记录管理的,当我跳转或者点击浏览器的后退按钮时,history就必须记录这些变化,而之前的react-router将history分为三类。

4.x之前版本的react-router针对三者分别实现了createHashHistory、createBrowserHistory和create MemoryHistory三个方法来创建三种情况下的history,这里就不讨论他们不同的处理方式了,好奇的可以去了解一下~到了4.x版本,在react-router-dom中直接将这三种history作了内置,于是我们看到了BrowserRouter、HashRouter、MemoryRouter这三种Router,当然,你依然可以使用React-router中的Router,然后自己通过createHistory来创建history来传入。
react-router的history库依然使用的是 https://github.com/ReactTraining/history

4. Route标签

在例子中你可能注意到了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
  }, {})
}

5. Link

还记得上面说到的改变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方法.

6. Redirect

我想单独再多说一下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。

7. withRouter

可以用withRouter结合this.props.history.push()实现点击按钮跳转
具体可以看Programmatically navigate using react router

参考文章

上一篇下一篇

猜你喜欢

热点阅读