學(xué)習(xí)React-router 4.x版本

這幾天閑下來想開發(fā)我個人網(wǎng)站的極客教程的移動web版本,然后發(fā)現(xiàn)之前弄的開發(fā)移動web的環(huán)境過于老舊,于是重新弄了個結(jié)合現(xiàn)在最新的相關(guān)庫的環(huán)境,相關(guān)文章可以看搭建我的網(wǎng)站的mobile版的開發(fā)環(huán)境

這不,剛弄好開發(fā)環(huán)境,準(zhǔn)備大顯身手一番,然而一來就碰壁了,卡在react-router路由這里,怎么都報錯,搞了一會,都懷疑人生了。然后我就猜測是react-router的版本問題,果不其然,默認(rèn)安裝的新版本跟以前的用法稍微有點(diǎn)不一樣的;我安裝的版本是 4.2.0版本的。接下來,就是學(xué)習(xí)一下新的react-router寫法及特性

1. 準(zhǔn)備

需要在你的react app中安裝:

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

如果你沒有相關(guān)react app 可以參照搭建我的網(wǎng)站的mobile版的開發(fā)環(huán)境,就是用create-react-app 快速搭建一個開發(fā)環(huán)境。

2. 使用

直接上例子吧,如果你是用create-react-app搭建的環(huán)境,就直接復(fù)制下面的代碼運(yùn)行吧,運(yùn)行效果就出來了。

//好了接下來我們直接路由
//打開demo文件下的src文件夾,直接修改 App.js 

import React from 'react'
import {BrowserRouter as Router,Route,Link} from 'react-router-dom'//導(dǎo)入的方式跟之前有點(diǎn)變化

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>點(diǎn)擊上邊的列表項(xiàng)此處顯示與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下面可以放任意標(biāo)簽了,這意味著使用方式的轉(zhuǎn)變,它更像redux中的provider了。通過上面的例子相信你也可以看到具體的變化。而真正的路由通過Route來定義。Link標(biāo)簽?zāi)壳翱磥硪矝]什么變化,依然可以理解為a標(biāo)簽,點(diǎn)擊會改變?yōu)g覽器Url的hash值,通過Route標(biāo)簽來捕獲這個url并返回component屬性中定義的組件,你可能注意到在為"/"寫的路由中有一個exact關(guān)鍵字,這個關(guān)鍵字是將"/"做唯一匹配,否則"/"和"/xxx"都會匹配到path為"/"的路由,制定exact后,"/"就不會再匹配到"/xxx"了。如果你不懂,動手試一下~

通過Route路由的組件,可以拿到一個match參數(shù),這個參數(shù)是一個對象,其中包含幾個數(shù)據(jù):

  • isExact:剛才已經(jīng)說過這個關(guān)鍵字,表示是為作全等匹配
  • params:path中包含的一些額外數(shù)據(jù)
  • path:Route組件path屬性的值
  • url:實(shí)際url的hash值

3. Router標(biāo)簽

細(xì)心的朋友肯定注意到了上面的例子中我import的Router是BrowserRouter,這是什么東西呢?如果你用過老版本的react-router,你一定知道history。history是用來兼容不同瀏覽器或者環(huán)境下的歷史記錄管理的,當(dāng)我跳轉(zhuǎn)或者點(diǎn)擊瀏覽器的后退按鈕時,history就必須記錄這些變化,而之前的react-router將history分為三類。

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

4.x之前版本的react-router針對三者分別實(shí)現(xiàn)了createHashHistory、createBrowserHistory和create MemoryHistory三個方法來創(chuàng)建三種情況下的history,這里就不討論他們不同的處理方式了,好奇的可以去了解一下~到了4.x版本,在react-router-dom中直接將這三種history作了內(nèi)置,于是我們看到了BrowserRouter、HashRouter、MemoryRouter這三種Router,當(dāng)然,你依然可以使用React-router中的Router,然后自己通過createHistory來創(chuàng)建history來傳入。
react-router的history庫依然使用的是 https://github.com/ReactTraining/history

4. Route標(biāo)簽

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

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

他們都不是必填項(xiàng),注意,如果path沒有賦值,那么此Route就是默認(rèn)渲染的。
Route的作用就是當(dāng)url和Route中path屬性的值匹配時,就渲染component中的組件或者render中的內(nèi)容。

當(dāng)然,Route其實(shí)還有幾個屬性,比如location,strict,chilren 希望你們自己去了解一下。

說到這,那么Route的內(nèi)部是怎樣實(shí)現(xiàn)這個機(jī)制的呢?不難猜測肯定是用一個匹配的方法來實(shí)現(xiàn)的,那么Route是怎么知道url更新了然后進(jìn)行重新匹配并渲染的呢?

整理一下思路,在一個web 應(yīng)用中,改變url無非是2種方式,一種是利用超鏈接進(jìn)行跳轉(zhuǎn),另一種是使用瀏覽器的前進(jìn)和回退功能。前者的在觸發(fā)Link的跳轉(zhuǎn)事件之后觸發(fā),而后者呢?Route利用的是我們上面說到過的history的listen方法來監(jiān)聽url的變化。為了防止引入新的庫,Route的創(chuàng)作者選擇了使用html5中的popState事件,只要點(diǎn)擊了瀏覽器的前進(jìn)或者后退按鈕,這個事件就會觸發(fā),我們來看一下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 (
      //有趣的是從這里我們可以看出各屬性渲染的優(yōu)先級,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
            )
    )
  }
}

這里只貼出了關(guān)鍵代碼,如果你使用過React,相信你能看懂,Route在組件將要Mount的時候添加popState事件的監(jiān)聽,每當(dāng)popState事件觸發(fā),就使用forceUpdate強(qiáng)制刷新,從而基于當(dāng)前的location.pathname進(jìn)行一次匹配,再根據(jù)結(jié)果渲染。

PS:現(xiàn)在最新的代碼中,Route源碼其實(shí)是通過componentWillReceiveProps中setState來實(shí)現(xiàn)重新渲染的,match屬性是作為Route組件的state存在的.

那么這個關(guān)鍵的matchPath方法是怎么實(shí)現(xiàn)的呢?
Route引入了一個外部library:path-to-regexp。這個pathToRegexp方法用于返回一個滿足要求的正則表達(dá)式,舉個例子:

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 = []

關(guān)于它的詳細(xì)信息你可以看這里:https://github.com/pillarjs/path-to-regexp
值得一提的是matchPath方法中對匹配結(jié)果作了緩存,如果是已經(jīng)匹配過的字符串,就不用再進(jìn)行一次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,看一下它的參數(shù):

static propTypes = {
    onClick: PropTypes.func,
    target: PropTypes.string,
    replace: PropTypes.bool,
    to: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.object
    ]).isRequired
}

onClick就不說了,target屬性就是a標(biāo)簽的target屬性,to相當(dāng)于href。
而replace的意思跳轉(zhuǎn)的鏈接是否覆蓋history中當(dāng)前的url,若為true,新的url將會覆蓋history中的當(dāng)前值,而不是向其中添加一個新的。

handleClick = (event) => {
  if (this.props.onClick)
    this.props.onClick(event)

  if (
    !event.defaultPrevented && // 是否阻止了默認(rèn)事件
    event.button === 0 && // 確定是鼠標(biāo)左鍵點(diǎn)擊
    !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

我想單獨(dú)再多說一下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結(jié)合this.props.history.push()實(shí)現(xiàn)點(diǎn)擊按鈕跳轉(zhuǎn)
具體可以看Programmatically navigate using react router

參考文章

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容