react-router@4.0 使用和源碼解析

若是你已是一個正在開發中的react應用,想要引入更好的管理路由功能。那麼,react-router是你最好的選擇~
react-router版本現今已經到4.0.0了,而上一個穩定版本仍是2.8.1。相信我,若是你的項目中已經在使用react-router以前的版本,那必定要慎重的更新,由於新的版本是一次很是大的改動,若是你要更新,工做量並不小。
這篇文章不討論版本的變化,只是討論一下React-router4.0的用法和源碼。
源碼在這裏:https://github.com/ReactTraining/react-routerhtml

1.準備

只須要在你的react app中引入一個包
yarn add react-router-dom@next
注:react-router-dom是對react-router的做了一些小升級的庫,代碼基於react-routerhtml5

 

2.使用

咱們直接上例子:node

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"就不會再匹配到"/"了。若是你不懂,動手試一下~react

經過Route路由的組件,能夠拿到一個match參數,這個參數是一個對象,其中包含幾個數據:git

  • isExact:剛纔已經說過這個關鍵字,表示是爲做全等匹配
  • params:path中包含的一些額外數據
  • path:Route組件path屬性的值
  • url:實際url的hash值

咱們來實現一下剛纔的Page2組件:github

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中的屬性傳遞給組件,屬性名就是冒號後的字符串。web

3.Router標籤

細心的朋友確定注意到了上面的例子中我import的Router是BrowserRouter,這是什麼東西呢?若是你用過老版本的react-router,你必定知道history。history是用來兼容不一樣瀏覽器或者環境下的歷史記錄管理的,當我跳轉或者點擊瀏覽器的後退按鈕時,history就必須記錄這些變化,而以前的react-router將history分爲三類。正則表達式

  • hashHistory 老版本瀏覽器的history
  • browserHistory h5的history
  • memoryHistory node環境下的history,存儲在memory中

4.0以前版本的react-router針對三者分別實現了createHashHistory、createBrowserHistory和create MemoryHistory三個方法來建立三種狀況下的history,這裏就不討論他們不一樣的處理方式了,好奇的能夠去了解一下~
到了4.0版本,在react-router-dom中直接將這三種history做了內置,因而咱們看到了BrowserRouter、HashRouter、MemoryRouter這三種Router,固然,你依然可使用React-router中的Router,而後本身經過createHistory來建立history來傳入。redux

react-router的history庫依然使用的是 https://github.com/ReactTraining/history瀏覽器

4.Route標籤

在例子中你可能注意到了Route的幾個prop

  • exact: propType.bool
  • path: propType.string
  • component: propType.func
  • render: propType.func

他們都不是必填項,注意,若是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。很容易產生這樣一個疑問,既然沒有UI爲何react-router的創造者依然選擇將Redirect寫成一個組件呢?

我想咱們能夠從做者口中的"Just Components API"中窺得緣由吧。

但願這篇文章能夠幫助你更好的建立你的React應用.

 

文章來自   http://www.jianshu.com/p/27ee7df4ccc1

相關文章
相關標籤/搜索