如果你已經(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í)的庫嫉沽,代碼基于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>
)
}
很簡單,動(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庫依然使用的是 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ī)制的呢?不難猜測肯定是用一個(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方法中對(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)用.