深入理解react-router路由的實現(xiàn)原理

React Router 是一個基于 React 之上的強大路由庫,它可以讓你向應(yīng)用中快速地添加視圖和數(shù)據(jù)流,同時保持頁面與 URL 間的同步。本文從兩個方便來解析 react-router 實現(xiàn)原理。一:介紹 react-router 的依賴庫history;二:使用 history 庫,實現(xiàn)一個簡單的 react-router 路由。

成都創(chuàng)新互聯(lián)專注于韶山企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè)公司,電子商務(wù)商城網(wǎng)站建設(shè)。韶山網(wǎng)站建設(shè)公司,為韶山等地區(qū)提供建站服務(wù)。全流程定制設(shè)計,專業(yè)設(shè)計,全程項目跟蹤,成都創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)

history 介紹

history 是一個 JavaScript 庫,可讓您在 JavaScript 運行的任何地方輕松管理會話歷史記錄。history 抽象出各種環(huán)境中的差異,并提供最小的 API ,使您可以管理歷史堆棧,導(dǎo)航,確認(rèn)導(dǎo)航以及在會話之間保持狀態(tài)。

history 有三種實現(xiàn)方式:

1、BrowserHistory:用于支持 HTML5 歷史記錄 API 的現(xiàn)代 Web 瀏覽器(請參閱跨瀏覽器兼容性)
2、HashHistory:用于舊版Web瀏覽器
3、MemoryHistory:用作參考實現(xiàn),也可用于非 DOM 環(huán)境,如 React Native 或測試

三種實現(xiàn)方法,都是創(chuàng)建了一個 history 對象,這里主要講下前面兩種:

const history = {
 length: globalHistory.length, 
 action: "POP", 
 location: initialLocation,
 createHref,
 push, // 改變location
 replace,
 go,
 goBack,
 goForward,
 block,
 listen //監(jiān)聽路由變化
};

1.頁面跳轉(zhuǎn)實現(xiàn)

BrowserHistory:pushState、replaceState;

HashHistory:location.hash、location.replace

function push(){
 createKey(); // 創(chuàng)建location的key,用于唯一標(biāo)示該location,是隨機生成的
 if(BrowserHistory){
 globalHistory.pushState({ key, state }, null, href);
 }else if(HashHistory){
 window.location.hash = path;
 }
 //上報listener 更新state ...
}
function replace(){
 createKey(); // 創(chuàng)建location的key,用于唯一標(biāo)示該location,是隨機生成的
 if(BrowserHistory){
 globalHistory.replaceState({ key, state }, null, href); 
 }else if(HashHistory){
 window.location.replace(window.location.href.slice(0, hashIndex >= 0 ? hashIndex : 0) + "#" path);
 } 
 //上報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=()=>{
 //上報listener
 transitionManager.notifyListeners();
 });
}

通過 history 實現(xiàn)簡單 react-router

import { Component } from 'react';
import createHistory from 'history/createHashHistory';
const history = createHistory(); //創(chuàng)建 history 對象
/**
 * 配置路由表
 * @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}`); //獲取路由對應(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在項目中已有大量實踐,其優(yōu)點可以總結(jié)如下:

風(fēng)格: 與React融為一體,專為react量身打造,編碼風(fēng)格與react保持一致,例如路由的配置可以通過component來實現(xiàn)

簡單: 不需要手工維護(hù)路由state,使代碼變得簡單

強大: 強大的路由管理機制,體現(xiàn)在如下方面

  • 路由配置: 可以通過組件、配置對象來進(jìn)行路由的配置
  • 路由切換: 可以通過<Link> Redirect進(jìn)行路由的切換
  • 路由加載: 可以同步記載,也可以異步加載,這樣就可以實現(xiàn)按需加載

使用方式: 不僅可以在瀏覽器端的使用,而且可以在服務(wù)器端的使用

當(dāng)然react-router的缺點就是API不太穩(wěn)定,在升級版本的時候需要進(jìn)行代碼變動。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

當(dāng)前標(biāo)題:深入理解react-router路由的實現(xiàn)原理
網(wǎng)站鏈接:http://muchs.cn/article0/iehpoo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站內(nèi)鏈、品牌網(wǎng)站建設(shè)、網(wǎng)站建設(shè)、企業(yè)網(wǎng)站制作、響應(yīng)式網(wǎng)站、外貿(mào)建站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)