国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > JS > 正文

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

2024-05-06 16:37:23
字體:
來源:轉載
供稿:網友

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

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

這篇文章不討論版本的變化,只是討論一下React-router4.0的用法和源碼。

源碼在這里:https://github.com/ReactTraining/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下面可以放任意標簽了,這意味著使用方式的轉變,它更像redux中的provider了。通過上面的例子相信你也可以看到具體的變化。而真正的路由通過Route來定義。Link標簽目前看來也沒什么變化,依然可以理解為a標簽,點擊會改變瀏覽器Url的hash值,通過Route標簽來捕獲這個url并返回component屬性中定義的組件,你可能注意到在為"/"寫的路由中有一個exact關鍵字,這個關鍵字是將"/"做唯一匹配,否則"/"和"/xxx"都會匹配到path為"/"的路由,制定exact后,"/page1"就不會再匹配到"/"了。如果你不懂,動手試一下~

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

  1. isExact:剛才已經說過這個關鍵字,表示是為作全等匹配
  2. params:path中包含的一些額外數據
  3. path:Route組件path屬性的值
  4. url:實際url的hash值

我們來實現一下剛才的Page2組件:

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

3.Router標簽

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

  1. hashHistory 老版本瀏覽器的history
  2. browserHistory h5的history
  3. 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來傳入。

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中的內容。

當然,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 nullconst [ url, ...values ] = matchconst isExact = pathname === url//如果exact為true,需要pathname===urlif (exact && !isExact) return nullreturn { 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應用.

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 尼玛县| 平南县| 峡江县| 刚察县| 鹤壁市| 乐亭县| 静海县| 绥阳县| 奉贤区| 会东县| 长沙县| 拉孜县| 托克托县| 萝北县| 蕉岭县| 西昌市| 精河县| 手机| 香港 | 九龙坡区| 太白县| 枞阳县| 南岸区| 南陵县| 吉林市| 天津市| 修文县| 离岛区| 遂平县| 喀喇沁旗| 福州市| 吉林省| 古蔺县| 桑植县| 葵青区| 富顺县| 久治县| 衡南县| 资兴市| 新晃| 海城市|