我对于react-router路由原理的学习

目录

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

未完待更新。。。浏览器

相关文章
相关标签/搜索