深入理解react-router 路由的實(shí)現(xiàn)原理
React Router 是一個(gè)基于 React 之上的強(qiáng)大路由庫(kù),它可以讓你向應(yīng)用中快速地添加視圖和數(shù)據(jù)流,同時(shí)保持頁(yè)面與 URL 間的同步。本文從兩個(gè)方便來解析 react-router 實(shí)現(xiàn)原理。一:介紹 react-router 的依賴庫(kù)history;二:使用 history 庫(kù),實(shí)現(xiàn)一個(gè)簡(jiǎn)單的 react-router 路由。
history 介紹
history 是一個(gè) JavaScript 庫(kù),可讓您在 JavaScript 運(yùn)行的任何地方輕松管理會(huì)話歷史記錄。history 抽象出各種環(huán)境中的差異,并提供最小的 API ,使您可以管理歷史堆棧,導(dǎo)航,確認(rèn)導(dǎo)航以及在會(huì)話之間保持狀態(tài)。
history 有三種實(shí)現(xiàn)方式:
1、BrowserHistory:用于支持 HTML5 歷史記錄 API 的現(xiàn)代 Web 瀏覽器(請(qǐng)參閱跨瀏覽器兼容性)
2、HashHistory:用于舊版Web瀏覽器
3、MemoryHistory:用作參考實(shí)現(xiàn),也可用于非 DOM 環(huán)境,如 React Native 或測(cè)試
三種實(shí)現(xiàn)方法,都是創(chuàng)建了一個(gè) history 對(duì)象,這里主要講下前面兩種:
const history = { length: globalHistory.length, action: "POP", location: initialLocation, createHref, push, // 改變location replace, go, goBack, goForward, block, listen //監(jiān)聽路由變化 };
1.頁(yè)面跳轉(zhuǎn)實(shí)現(xiàn)
BrowserHistory:pushState、replaceState;
HashHistory:location.hash、location.replace
function push(){ createKey(); // 創(chuàng)建location的key,用于唯一標(biāo)示該location,是隨機(jī)生成的 if(BrowserHistory){ globalHistory.pushState({ key, state }, null, href); }else if(HashHistory){ window.location.hash = path; } //上報(bào)listener 更新state ... } function replace(){ createKey(); // 創(chuàng)建location的key,用于唯一標(biāo)示該location,是隨機(jī)生成的 if(BrowserHistory){ globalHistory.replaceState({ key, state }, null, href); }else if(HashHistory){ window.location.replace(window.location.href.slice(0, hashIndex >= 0 ? hashIndex : 0) + "#" path); } //上報(bào)listener 更新state ... }
2.瀏覽器回退
BrowserHistory:popstate;
HashHistory:hashchang;
if(BrowserHistory){ window.addEventListener("popstate", routerChange); }else if(HashHistory){ window.addEventListener("hashchange", routerChange); } function routerChange(){ const location = getDOMLocation(); //獲取location //路由切換 transitionManager.confirmTransitionTo(location,callback=()=>{ //上報(bào)listener transitionManager.notifyListeners(); }); }
通過 history 實(shí)現(xiàn)簡(jiǎn)單 react-router
import { Component } from 'react'; import createHistory from 'history/createHashHistory'; const history = createHistory(); //創(chuàng)建 history 對(duì)象 /** * 配置路由表 * @type {{"/": string}} */ const router = { '/': 'page/home/index', '/my': 'page/my/index' } export default class Router extends Component { state = { page: null } async route(location) { let pathname = location.pathname; let pagePath = router[pathname]; // 加 ./的原因 https://webpack.docschina.org/api/module-methods#import- const Page = await import(`./${pagePath}`); //獲取路由對(duì)應(yīng)的ui //設(shè)置ui this.setState({ Page: Page.default }); } initListener(){ //監(jiān)聽路由切換 history.listen((location, action) => { //切換路由后,更新ui this.route(location); }); } componentDidMount() { this.route(history.location); this.initListener(); } render() { const { Page } = this.state; return Page && <Page {...this.props} />; } }
目前react-router在項(xiàng)目中已有大量實(shí)踐,其優(yōu)點(diǎn)可以總結(jié)如下:
風(fēng)格: 與React融為一體,專為react量身打造,編碼風(fēng)格與react保持一致,例如路由的配置可以通過component來實(shí)現(xiàn)
簡(jiǎn)單: 不需要手工維護(hù)路由state,使代碼變得簡(jiǎn)單
強(qiáng)大: 強(qiáng)大的路由管理機(jī)制,體現(xiàn)在如下方面
- 路由配置: 可以通過組件、配置對(duì)象來進(jìn)行路由的配置
- 路由切換: 可以通過<Link> Redirect進(jìn)行路由的切換
- 路由加載: 可以同步記載,也可以異步加載,這樣就可以實(shí)現(xiàn)按需加載
使用方式: 不僅可以在瀏覽器端的使用,而且可以在服務(wù)器端的使用
當(dāng)然react-router的缺點(diǎn)就是API不太穩(wěn)定,在升級(jí)版本的時(shí)候需要進(jìn)行代碼變動(dòng)。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
React Native中實(shí)現(xiàn)動(dòng)態(tài)導(dǎo)入的示例代碼
隨著業(yè)務(wù)的發(fā)展,每一個(gè) React Native 應(yīng)用的代碼數(shù)量都在不斷增加。作為一個(gè)前端想到的方案自然就是動(dòng)態(tài)導(dǎo)入(Dynamic import)了,本文介紹了React Native中實(shí)現(xiàn)動(dòng)態(tài)導(dǎo)入的示例代碼,需要的可以參考一下2022-06-06詳解react如何實(shí)現(xiàn)復(fù)合組件
在一些react項(xiàng)目開發(fā)中,常常會(huì)出現(xiàn)一些組合的情況出現(xiàn),這篇文章主要為大家介紹了復(fù)合組件的具體實(shí)現(xiàn),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-10-10React Hook useState useEffect componentD
這篇文章主要介紹了React Hook useState useEffect componentDidMount componentDidUpdate componentWillUnmount問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03使用Electron構(gòu)建React+Webpack桌面應(yīng)用的方法
本篇文章主要介紹了使用Electron構(gòu)建React+Webpack桌面應(yīng)用的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-12-12Vite+React+TypeScript手?jǐn)]TodoList的項(xiàng)目實(shí)踐
本文主要介紹了Vite+React+TypeScript手?jǐn)]TodoList的項(xiàng)目實(shí)踐,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05React Native:react-native-code-push報(bào)錯(cuò)的解決
這篇文章主要介紹了React Native:react-native-code-push報(bào)錯(cuò)的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10React Native基礎(chǔ)入門之調(diào)試React Native應(yīng)用的一小步
這篇文章主要給大家介紹了關(guān)于React Native基礎(chǔ)入門之調(diào)試React Native應(yīng)用的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-07-07