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

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

history 介紹

history 是一個 JavaScript 庫,可讓您在 JavaScript 運行的任何地方輕松管理會話歷史記錄。history 抽象出各種環(huán)境中的差異,并提供最小的 API ,使您可以管理歷史堆棧,導航,確認導航以及在會話之間保持狀態(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,用于唯一標示該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,用于唯一標示該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}`); //獲取路由對應的ui
    //設置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} />;
  }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容