您好,登錄后才能下訂單哦!
如何實現(xiàn)一個ReactRouter?針對這個問題,這篇文章詳細介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
ReactRouter
是React
的核心組件,主要是作為React
的路由管理器,保持UI
與URL
同步,其擁有簡單的API
與強大的功能例如代碼緩沖加載、動態(tài)路由匹配、以及建立正確的位置過渡處理等。
React Router
是建立在history
對象之上的,簡而言之一個history
對象知道如何去監(jiān)聽瀏覽器地址欄的變化,并解析這個URL
轉(zhuǎn)化為location
對象,然后router
使用它匹配到路由,最后正確地渲染對應(yīng)的組件,常用的history
有三種形式: Browser History
、Hash History
、Memory History
。
Browser History
是使用React Router
的應(yīng)用推薦的history
,其使用瀏覽器中的History
對象的pushState
、replaceState
等API
以及popstate
事件等來處理URL
,其能夠創(chuàng)建一個像https://www.example.com/path
這樣真實的URL
,同樣在頁面跳轉(zhuǎn)時無須重新加載頁面,當(dāng)然也不會對于服務(wù)端進行請求,當(dāng)然對于history
模式仍然是需要后端的配置支持,用以支持非首頁的請求以及刷新時后端返回的資源,由于應(yīng)用是個單頁客戶端應(yīng)用,如果后臺沒有正確的配置,當(dāng)用戶在瀏覽器直接訪問URL
時就會返回404
,所以需要在服務(wù)端增加一個覆蓋所有情況的候選資源,如果URL
匹配不到任何靜態(tài)資源時,則應(yīng)該返回同一個index.html
應(yīng)用依賴頁面,例如在Nginx
下的配置。
location / { try_files $uri $uri/ /index.html; }
Hash
符號即#
原本的目的是用來指示URL
中指示網(wǎng)頁中的位置,例如https://www.example.com/index.html#print
即代表example
的index.html
的print
位置,瀏覽器讀取這個URL
后,會自動將print
位置滾動至可視區(qū)域,通常使用<a>
標簽的name
屬性或者<div>
標簽的id
屬性指定錨點。
通過window.location.hash
屬性能夠讀取錨點位置,可以為Hash
的改變添加hashchange
監(jiān)聽事件,每一次改變Hash
,都會在瀏覽器的訪問歷史中增加一個記錄,此外Hash
雖然出現(xiàn)在URL
中,但不會被包括在HTTP
請求中,即#
及之后的字符不會被發(fā)送到服務(wù)端進行資源或數(shù)據(jù)的請求,其是用來指導(dǎo)瀏覽器動作的,對服務(wù)器端沒有效果,因此改變Hash
不會重新加載頁面。ReactRouter
的作用就是通過改變URL
,在不重新請求頁面的情況下,更新頁面視圖,從而動態(tài)加載與銷毀組件,簡單的說就是,雖然地址欄的地址改變了,但是并不是一個全新的頁面,而是之前的頁面某些部分進行了修改,這也是SPA
單頁應(yīng)用的特點,其所有的活動局限于一個Web
頁面中,非懶加載的頁面僅在該Web
頁面初始化時加載相應(yīng)的HTML
、JavaScript
、CSS
文件,一旦頁面加載完成,SPA
不會進行頁面的重新加載或跳轉(zhuǎn),而是利用JavaScript
動態(tài)的變換HTML
,默認Hash
模式是通過錨點實現(xiàn)路由以及控制組件的顯示與隱藏來實現(xiàn)類似于頁面跳轉(zhuǎn)的交互。
Memory History
不會在地址欄被操作或讀取,這就可以解釋如何實現(xiàn)服務(wù)器渲染的,同時其也非常適合測試和其他的渲染環(huán)境例如React Native
,和另外兩種History
的一點不同是我們必須創(chuàng)建它,這種方式便于測試。
const history = createMemoryHistory(location);
我們來實現(xiàn)一個非常簡單的Browser History
模式與Hash History
模式的實現(xiàn),因為H5
的pushState
方法不能在本地文件協(xié)議file://
運行,所以運行起來需要搭建一個http://
環(huán)境,使用webpack
、Nginx
、Apache
等都可以,回到Browser History
模式路由,能夠?qū)崿F(xiàn)history
路由跳轉(zhuǎn)不刷新頁面得益與H5
提供的pushState()
、replaceState()
等方法以及popstate
等事件,這些方法都是也可以改變路由路徑,但不作頁面跳轉(zhuǎn),當(dāng)然如果在后端不配置好的情況下路由改編后刷新頁面會提示404
,對于Hash History
模式,我們的實現(xiàn)思路相似,主要在于沒有使用pushState
等H5
的API
,以及監(jiān)聽事件不同,通過監(jiān)聽其hashchange
事件的變化,然后拿到對應(yīng)的location.hash
更新對應(yīng)的視圖。
<!-- Browser History --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Router</title> </head> <body> <ul> <li><a href="/home" rel="external nofollow" >home</a></li> <li><a href="/about" rel="external nofollow" >about</a></li> <div id="routeView"></div> </ul> </body> <script> function Router() { this.routeView = null; // 組件承載的視圖容器 this.routes = Object.create(null); // 定義的路由 } // 綁定路由匹配后事件 Router.prototype.route = function (path, callback) { this.routes[path] = () => this.routeView.innerHTML = callback() || ""; }; // 初始化 Router.prototype.init = function(root, rootView) { this.routeView = rootView; // 指定承載視圖容器 this.refresh(); // 初始化即刷新視圖 root.addEventListener("click", (e) => { // 事件委托到root if (e.target.nodeName === "A") { e.preventDefault(); history.pushState(null, "", e.target.getAttribute("href")); this.refresh(); // 觸發(fā)即刷新視圖 } }) // 監(jiān)聽用戶點擊后退與前進 // pushState與replaceState不會觸發(fā)popstate事件 window.addEventListener("popstate", this.refresh.bind(this), false); }; // 刷新視圖 Router.prototype.refresh = function () { let path = location.pathname; console.log("refresh", path); if(this.routes[path]) this.routes[path](); else this.routeView.innerHTML = ""; }; window.Router = new Router(); Router.route("/home", function() { return "home"; }); Router.route("/about", function () { return "about"; }); Router.init(document, document.getElementById("routeView")); </script> </html>
<!-- Hash History --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Router</title> </head> <body> <ul> <li><a href="#/home" rel="external nofollow" >home</a></li> <li><a href="#/about" rel="external nofollow" >about</a></li> <div id="routeView"></div> </ul> </body> <script> function Router() { this.routeView = null; // 組件承載的視圖容器 this.routes = Object.create(null); // 定義的路由 } // 綁定路由匹配后事件 Router.prototype.route = function (path, callback) { this.routes[path] = () => this.routeView.innerHTML = callback() || ""; }; // 初始化 Router.prototype.init = function(root, rootView) { this.routeView = rootView; // 指定承載視圖容器 this.refresh(); // 初始化觸發(fā) // 監(jiān)聽hashchange事件用以刷新 window.addEventListener("hashchange", this.refresh.bind(this), false); }; // 刷新視圖 Router.prototype.refresh = function () { let hash = location.hash; console.log("refresh", hash); if(this.routes[hash]) this.routes[hash](); else this.routeView.innerHTML = ""; }; window.Router = new Router(); Router.route("#/home", function() { return "home"; }); Router.route("#/about", function () { return "about"; }); Router.init(document, document.getElementById("routeView")); </script> </html>
我們可以看一下ReactRouter
的實現(xiàn),commit id
為eef79d5
,TAG
是4.4.0
,在這之前我們需要先了解一下history
庫,history
庫,是ReactRouter
依賴的一個對window.history
加強版的history
庫,其中主要用到的有match
對象表示當(dāng)前的URL
與path
的匹配的結(jié)果,location
對象是history
庫基于window.location
的一個衍生。
ReactRouter
將路由拆成了幾個包: react-router
負責(zé)通用的路由邏輯,react-router-dom
負責(zé)瀏覽器的路由管理,react-router-native
負責(zé)react-native
的路由管理。
我們以BrowserRouter
組件為例,BrowserRouter
在react-router-dom
中,它是一個高階組件,在內(nèi)部創(chuàng)建一個全局的history
對象,可以監(jiān)聽整個路由的變化,并將history
作為props
傳遞給react-router
的Router
組件,Router
組件再會將這個history
的屬性作為context
傳遞給子組件。
// packages\react-router-dom\modules\HashRouter.js line 10 class BrowserRouter extends React.Component { history = createHistory(this.props); render() { return <Router history={this.history} children={this.props.children} />; } }
接下來我們到Router
組件,Router
組件創(chuàng)建了一個React Context
環(huán)境,其借助context
向Route
傳遞context
,這也解釋了為什么Router
要在所有Route
的外面。在Router
的componentWillMount
中,添加了history.listen
,其能夠監(jiān)聽路由的變化并執(zhí)行回調(diào)事件,在這里即會觸發(fā)setState
。當(dāng)setState
時即每次路由變化時 ->
觸發(fā)頂層Router
的回調(diào)事件 ->
Router
進行setState
->
向下傳遞 nextContext
此時context
中含有最新的location
->
下面的Route
獲取新的nextContext
判斷是否進行渲染。
// line packages\react-router\modules\Router.js line 10 class Router extends React.Component { static computeRootMatch(pathname) { return { path: "/", url: "/", params: {}, isExact: pathname === "/" }; } constructor(props) { super(props); this.state = { location: props.history.location }; // This is a bit of a hack. We have to start listening for location // changes here in the constructor in case there are any <Redirect>s // on the initial render. If there are, they will replace/push when // they mount and since cDM fires in children before parents, we may // get a new location before the <Router> is mounted. this._isMounted = false; this._pendingLocation = null; if (!props.staticContext) { this.unlisten = props.history.listen(location => { if (this._isMounted) { this.setState({ location }); } else { this._pendingLocation = location; } }); } } componentDidMount() { this._isMounted = true; if (this._pendingLocation) { this.setState({ location: this._pendingLocation }); } } componentWillUnmount() { if (this.unlisten) this.unlisten(); } render() { return ( <RouterContext.Provider children={this.props.children || null} value={{ history: this.props.history, location: this.state.location, match: Router.computeRootMatch(this.state.location.pathname), staticContext: this.props.staticContext }} /> ); } }
我們在使用時都是使用Router
來嵌套Route
,所以此時就到Route
組件,Route
的作用是匹配路由,并傳遞給要渲染的組件props
,Route
接受上層的Router
傳入的context
,Router
中的history
監(jiān)聽著整個頁面的路由變化,當(dāng)頁面發(fā)生跳轉(zhuǎn)時,history
觸發(fā)監(jiān)聽事件,Router
向下傳遞nextContext
,就會更新Route
的props
和context
來判斷當(dāng)前Route
的path
是否匹配location
,如果匹配則渲染,否則不渲染,是否匹配的依據(jù)就是computeMatch
這個函數(shù),在下文會有分析,這里只需要知道匹配失敗則match
為null
,如果匹配成功則將match
的結(jié)果作為props
的一部分,在render
中傳遞給傳進來的要渲染的組件。Route
接受三種類型的render props
,<Route component>
、<Route render>
、<Route children>
,此時要注意的是如果傳入的component
是一個內(nèi)聯(lián)函數(shù),由于每次的props.component
都是新創(chuàng)建的,所以React
在diff
的時候會認為進來了一個全新的組件,所以會將舊的組件unmount
再re-mount
。這時候就要使用render
,少了一層包裹的component
元素,render
展開后的元素類型每次都是一樣的,就不會發(fā)生re-mount
了,另外children
也不會發(fā)生re-mount
。
// \packages\react-router\modules\Route.js line 17 class Route extends React.Component { render() { return ( <RouterContext.Consumer> {context => { invariant(context, "You should not use <Route> outside a <Router>"); const location = this.props.location || context.location; const match = this.props.computedMatch ? this.props.computedMatch // <Switch> already computed the match for us : this.props.path ? matchPath(location.pathname, this.props) : context.match; const props = { ...context, location, match }; let { children, component, render } = this.props; // Preact uses an empty array as children by // default, so use null if that's the case. if (Array.isArray(children) && children.length === 0) { children = null; } if (typeof children === "function") { children = children(props); // ... } return ( <RouterContext.Provider value={props}> {children && !isEmptyChildren(children) ? children : props.match ? component ? React.createElement(component, props) : render ? render(props) : null : null} </RouterContext.Provider> ); }} </RouterContext.Consumer> ); } }
我們實際上我們可能寫的最多的就是Link
這個標簽了,所以我們再來看一下<Link>
組件,我們可以看到Link
最終還是創(chuàng)建一個a
標簽來包裹住要跳轉(zhuǎn)的元素,在這個a
標簽的handleClick
點擊事件中會preventDefault
禁止默認的跳轉(zhuǎn),所以實際上這里的href
并沒有實際的作用,但仍然可以標示出要跳轉(zhuǎn)到的頁面的URL
并且有更好的html
語義。在handleClick
中,對沒有被preventDefault
、鼠標左鍵點擊的、非_blank
跳轉(zhuǎn)的、沒有按住其他功能鍵的單擊進行preventDefault
,然后push
進history
中,這也是前面講過的路由的變化與 頁面的跳轉(zhuǎn)是不互相關(guān)聯(lián)的,ReactRouter
在Link
中通過history
庫的push
調(diào)用了HTML5 history
的pushState
,但是這僅僅會讓路由變化,其他什么都沒有改變。在Router
中的listen
,它會監(jiān)聽路由的變化,然后通過context
更新props
和nextContext
讓下層的Route
去重新匹配,完成需要渲染部分的更新。
// packages\react-router-dom\modules\Link.js line 14 class Link extends React.Component { handleClick(event, history) { if (this.props.onClick) this.props.onClick(event); if ( !event.defaultPrevented && // onClick prevented default event.button === 0 && // ignore everything but left clicks (!this.props.target || this.props.target === "_self") && // let browser handle "target=_blank" etc. !isModifiedEvent(event) // ignore clicks with modifier keys ) { event.preventDefault(); const method = this.props.replace ? history.replace : history.push; method(this.props.to); } } render() { const { innerRef, replace, to, ...rest } = this.props; // eslint-disable-line no-unused-vars return ( <RouterContext.Consumer> {context => { invariant(context, "You should not use <Link> outside a <Router>"); const location = typeof to === "string" ? createLocation(to, null, null, context.location) : to; const href = location ? context.history.createHref(location) : ""; return ( <a {...rest} onClick={event => this.handleClick(event, context.history)} href={href} ref={innerRef} /> ); }} </RouterContext.Consumer> ); } }
關(guān)于如何實現(xiàn)一個ReactRouter問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。