我对于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

未完待更新。。。