溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

react-router@4.0怎么用

發(fā)布時(shí)間:2021-08-05 09:46:55 來源:億速云 閱讀:124 作者:小新 欄目:web開發(fā)

這篇文章主要介紹了react-router@4.0怎么用,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

如果你已經(jīng)是一個(gè)正在開發(fā)中的react應(yīng)用,想要引入更好的管理路由功能。那么,react-router是你最好的選擇~

react-router版本現(xiàn)今已經(jīng)到4.0.0了,而上一個(gè)穩(wěn)定版本還是2.8.1。相信我,如果你的項(xiàng)目中已經(jīng)在使用react-router之前的版本,那一定要慎重的更新,因?yàn)樾碌陌姹臼且淮畏浅4蟮母膭?dòng),如果你要更新,工作量并不小。

1.準(zhǔn)備

只需要在你的react app中引入一個(gè)包yarn add react-router-dom@next

注:react-router-dom是對react-router的作了一些小升級(jí)的庫,代碼基于react-router

2.使用

我們直接上例子:

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

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

  1. isExact:剛才已經(jīng)說過這個(gè)關(guān)鍵字,表示是為作全等匹配

  2. params:path中包含的一些額外數(shù)據(jù)

  3. path:Route組件path屬性的值

  4. url:實(shí)際url的hash值

我們來實(shí)現(xiàn)一下剛才的Page2組件:

const Page2 = ({ match }) => (
 <div>
 <h3>Page2</h3>
 <ul>
  <li>
  <Link to={`${match.url}/branch2`}>
   branch2
  </Link>
  </li>
  <li>
  <Link to={`${match.url}/branch3`}>
   branch3
  </Link>
  </li>
  <li>
  <Link to={`${match.url}/branch4`}>
   branch4
  </Link>
  </li>
 </ul>

 <Route path={`${match.url}/:branchId`} component={Branch} />
 <Route exact path={match.url} render={() => (
  <h4>Default Information</h4>
 )} />
 </div>
)

const Branch = ({ match }) => {
 console.log(match);
 return (
 <div>
  <h4>{match.params.branchId}</h4>
 </div>
 )
}

很簡單,動(dòng)手試一試。需要注意的就只有Route的path中冒號(hào)":"后的部分相當(dāng)于通配符,而匹配到的url將會(huì)把匹配的部分作為match.param中的屬性傳遞給組件,屬性名就是冒號(hào)后的字符串。

3.Router標(biāo)簽

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

  1. hashHistory 老版本瀏覽器的history

  2. browserHistory h6的history

  3. memoryHistory node環(huán)境下的history,存儲(chǔ)在memory中

4.0之前版本的react-router針對三者分別實(shí)現(xiàn)了createHashHistory、createBrowserHistory和create MemoryHistory三個(gè)方法來創(chuàng)建三種情況下的history,這里就不討論他們不同的處理方式了,好奇的可以去了解一下~
到了4.0版本,在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的幾個(gè)prop

  1. exact: propType.bool

  2. path: propType.string

  3. component: propType.func

  4. render: propType.func

他們都不是必填項(xiàng),注意,如果path沒有賦值,那么此Route就是默認(rèn)渲染的。

Route的作用就是當(dāng)url和Route中path屬性的值匹配時(shí),就渲染component中的組件或者render中的內(nèi)容。

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

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

整理一下思路,在一個(gè)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)或者后退按鈕,這個(gè)事件就會(huì)觸發(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是一個(gè)全局變量
 const match = matchPath(location.pathname, { path, exact })

 return (
  //有趣的是從這里我們可以看出各屬性渲染的優(yōu)先級(jí),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的時(shí)候添加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存在的.

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

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將會(huì)覆蓋history中的當(dāng)前值,而不是向其中添加一個(gè)新的。

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值,是否同時(shí)按下了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
 }
}

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“react-router@4.0怎么用”這篇文章對大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)
推薦閱讀:
  1. 怎么用vuex
  2. 怎么用redis

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI