我對於react-router路由原理的學習


目錄

react-router依賴基礎--history

react-router是如何實現URL與UI同步

一 react-router依賴基礎--history

history是一個獨立的第三方js庫,可以用來兼容不同的瀏覽器、不同環境下對歷史記錄的管理。具體可以分為以下幾類:

  • hashHistory:通常應用於老版本瀏覽器,主要通過hash來實現
  • browserHistory:通常應用於高版本瀏覽器,通過html5中的history來實現
  • memoryHistory:node環境中,主要存儲在memory中

三種實現方法,都是創建了一個history對象,這里主要講下前2個:

const history = {
    length: globalHistory.length,
    action: "props",
    location: initalLocation,
    createHref,
    push, // 改變location
    replace,
    go,
    goBack,
    goForward,
    block,
    listen //監聽路由變化
}

1 頁面的跳轉實現

BrowserHistory: pushState replactState
HashHistroy: location.hash location.replace

function push() {
    createKey(); // 創建location的key,用於唯一標識該location,是隨機生成的
    if (BrowserHistory) {
        globalHistory.pushState({ key, state }, null, href);
    } else if (HashHistory) {
        window.location.hash = path;
    }
    // 上報listener,更新state
}

function replace() {
    createKey();
    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: hashchange

function pop() {
    if (BrowserHistory) {
        window.addEventListener("popstate", routerChange);
    } else if (HashHistory) {
        window.addEventListener("hashChange", routerChange);
    }
}

function routerChange() {
    const location = getDOMLocation(); //獲取location
    transitionManger.confirmTransitionTo(location,  callback = () => {      // 路由切換
        transitionManager.notifyListeners();  // 上報listener
    })
}

二 react-router是如何實現URL與UI同步

通過history實現一個簡單地react-router

未完待更新。。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM