深入理解react-router@4.0 使用和源碼解析
如果你已經(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),如果你要更新,工作量并不小。
這篇文章不討論版本的變化,只是討論一下React-router4.0的用法和源碼。
源碼在這里:https://github.com/ReactTraining/react-router
1.準(zhǔn)備
只需要在你的react app中引入一個(gè)包yarn add react-router-dom@next
注:react-router-dom是對(duì)react-router的作了一些小升級(jí)的庫(kù),代碼基于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è)對(duì)象,其中包含幾個(gè)數(shù)據(jù):
- isExact:剛才已經(jīng)說過這個(gè)關(guān)鍵字,表示是為作全等匹配
- params:path中包含的一些額外數(shù)據(jù)
- path:Route組件path屬性的值
- url:實(shí)際url的hash值
我們來實(shí)現(xiàn)一下剛才的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>
)
}
很簡(jiǎn)單,動(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分為三類。
- hashHistory 老版本瀏覽器的history
- browserHistory h5的history
- memoryHistory node環(huán)境下的history,存儲(chǔ)在memory中
4.0之前版本的react-router針對(duì)三者分別實(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庫(kù)依然使用的是 https://github.com/ReactTraining/history
4.Route標(biāo)簽
在例子中你可能注意到了Route的幾個(gè)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屬性的值匹配時(shí),就渲染component中的組件或者render中的內(nèi)容。
當(dāng)然,Route其實(shí)還有幾個(gè)屬性,比如location,strict,chilren 希望你們自己去了解一下。
說到這,那么Route的內(nèi)部是怎樣實(shí)現(xiàn)這個(gè)機(jī)制的呢?不難猜測(cè)肯定是用一個(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的變化。為了防止引入新的庫(kù),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方法中對(duì)匹配結(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
}
}
很容易注意到這個(gè)組件并沒有UI,render方法return了一個(gè)null。很容易產(chǎn)生這樣一個(gè)疑問,既然沒有UI為什么react-router的創(chuàng)造者依然選擇將Redirect寫成一個(gè)組件呢?
我想我們可以從作者口中的"Just Components API"中窺得原因吧。
希望這篇文章可以幫助你更好的創(chuàng)建你的React應(yīng)用.
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
React router cache route實(shí)現(xiàn)緩存頁(yè)面流程介紹
react-router自身沒有路由緩存的特性,在5.x版本之前,我們可以基于react-router-cache-route來實(shí)現(xiàn)路由緩存功能。但是react-router 6.x在實(shí)現(xiàn)上做了比較大的變化,react-router-cache-route沒有提供相應(yīng)的支持2023-01-01
使用react實(shí)現(xiàn)手機(jī)號(hào)的數(shù)據(jù)同步顯示功能的示例代碼
本篇文章主要介紹了使用react實(shí)現(xiàn)手機(jī)號(hào)的數(shù)據(jù)同步顯示功能的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-04-04
React Native實(shí)現(xiàn)簡(jiǎn)單的登錄功能(推薦)
這篇文章主要介紹了React Native實(shí)現(xiàn)登錄功能的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-09-09
React性能優(yōu)化的實(shí)現(xiàn)方法詳解
react憑借virtual DOM和diff算法擁有高效的性能,除此之外也有很多其他的方法和技巧可以進(jìn)一步提升react性能,在本文中我將列舉出可有效提升react性能的幾種方法,幫助我們改進(jìn)react代碼,提升性能2023-01-01
React?Native項(xiàng)目設(shè)置路徑別名示例
這篇文章主要為大家介紹了React?Native項(xiàng)目設(shè)置路徑別名實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05

