目錄
react-router依賴基礎--history
react-router是如何實現URL與UI同步
一 react-router依賴基礎--history
history是一個獨立的第三方js庫,能夠用來兼容不一樣的瀏覽器、不一樣環境下對歷史記錄的管理。具體能夠分爲如下幾類:html
- hashHistory:一般應用於老版本瀏覽器,主要經過hash來實現
- browserHistory:一般應用於高版本瀏覽器,經過html5中的history來實現
- memoryHistory:node環境中,主要存儲在memory中
三種實現方法,都是建立了一個history對象,這裏主要講下前2個:html5
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.replacenode
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: hashchangereact
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
未完待更新。。。瀏覽器