react-router@4.0怎么用

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

越秀網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)建站!從網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、響應(yīng)式網(wǎng)站設(shè)計等網(wǎng)站項目制作,到程序開發(fā),運營維護。創(chuàng)新互聯(lián)建站從2013年創(chuàng)立到現(xiàn)在10年的時間,我們擁有了豐富的建站經(jīng)驗和運維經(jīng)驗,來保證我們的工作的順利進行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)建站

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

react-router版本現(xiàn)今已經(jīng)到4.0.0了,而上一個穩(wěn)定版本還是2.8.1。相信我,如果你的項目中已經(jīng)在使用react-router之前的版本,那一定要慎重的更新,因為新的版本是一次非常大的改動,如果你要更新,工作量并不小。

1.準備

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

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

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

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

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

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

  4. url:實際url的hash值

我們來實現(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>
 )
}

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

3.Router標簽

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

  1. hashHistory 老版本瀏覽器的history

  2. browserHistory h6的history

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

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

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

4.Route標簽

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

  1. exact: propType.bool

  2. path: propType.string

  3. component: propType.func

  4. render: propType.func

他們都不是必填項,注意,如果path沒有賦值,那么此Route就是默認渲染的。

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

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

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

整理一下思路,在一個web 應(yīng)用中,改變url無非是2種方式,一種是利用超鏈接進行跳轉(zhuǎn),另一種是使用瀏覽器的前進和回退功能。前者的在觸發(fā)Link的跳轉(zhuǎn)事件之后觸發(fā),而后者呢?Route利用的是我們上面說到過的history的listen方法來監(jiān)聽url的變化。為了防止引入新的庫,Route的創(chuàng)作者選擇了使用html5中的popState事件,只要點擊了瀏覽器的前進或者后退按鈕,這個事件就會觸發(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)聽,每當popState事件觸發(fā),就使用forceUpdate強制刷新,從而基于當前的location.pathname進行一次匹配,再根據(jù)結(jié)果渲染。

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

那么這個關(guān)鍵的matchPath方法是怎么實現(xiàn)的呢?
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 = []

關(guān)于它的詳細信息你可以看這里:https://github.com/pillarjs/path-to-regexp

值得一提的是matchPath方法中對匹配結(jié)果作了緩存,如果是已經(jīng)匹配過的字符串,就不用再進行一次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標簽的target屬性,to相當于href。

而replace的意思跳轉(zhuǎn)的鏈接是否覆蓋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
 }
}

感謝你能夠認真閱讀完這篇文章,希望小編分享的“react-router@4.0怎么用”這篇文章對大家有幫助,同時也希望大家多多支持創(chuàng)新互聯(lián),關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關(guān)知識等著你來學習!

本文名稱:react-router@4.0怎么用
標題路徑:http://bm7419.com/article10/igogdo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供服務(wù)器托管、全網(wǎng)營銷推廣網(wǎng)站排名、網(wǎng)站策劃、虛擬主機、定制網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司