react-router的原理分析
react-router中涉及到的组件有如下几个:history、Router、Route、Link。可以通过API文档来查看具体的使用,在这里仅仅介绍其基本功能和实现的原理。
一、组件的功能
1、history:React Router 是建立在 history 之上的。 简而言之,一个 history 知道如何去监听浏览器地址栏的变化, 并解析这个 URL 转化为location对象, 然后 router 使用它匹配到路由,最后正确地渲染对应的组件。
2、Router: 负责根据当前的url来渲染相对应的component。
3、Route:是用于声明路由映射到应用程序的组件层,其实就是会根据当前url,来与本身的path属性去匹配,如果匹配成功,那么就渲染Component属性中的组件。
二、实现原理
1、history:react-router中的history有三种,分别是browserHistory、hashHistory、menoryHistory,其中最常用的是前两种。其中,browserHistory利用的是H5中的History接口,hashHistory利用的history中location属性的hash。
1) browserHistory:browserHistory中采用push和replace方法来实现url的改变,这两个方法分别封装了history对象的pushState和replaceState方法。这两个方法都会改变当前的url,但是不会刷新当前页面。
History.pushState()可以将给定的数据压入浏览器回话的历史栈中,该方法接受3个参数,分别是对象、title和url。
History.replaceState()可以将当前的页面url替换成指定的数据。
当browserHistory通过调用以上两个方法改变了当前会话窗口的url后,怎么才能监听到这个改变呢?
History中的同样可以改变url的方法有back()、forward()、go(),这些方法都会触发popState事件,所以在这里browserHistory采用手动触发popState的方式来实现对url改变的监听,如下图所示代码段中的window.addEventListener。
var listenerCount = 0;
function checkDOMListeners(delta) {
listenerCount += delta;
if (listenerCount === 1 && delta === 1) {
window.addEventListener(PopStateEvent, handlePopState); //手动调用popState事件
if (needsHashChangeListener) window.addEventListener(HashChangeEvent, handleHashChange);
} else if (listenerCount === 0) {
window.removeEventListener(PopStateEvent, handlePopState);
if (needsHashChangeListener) window.removeEventListener(HashChangeEvent, handleHashChange);
}
}
2)hashHistory: hashHistory通过区分history对象的location属性中包含的hash字段来渲染不同的component。其中hash字段的改变是不会引起页面刷新的。
在browserHistory中通过手动调用popState事件来实现对url的监听,那么当hash改变时如何监听呢,在这里History对象提供了hashchange事件,当hash改变时会自动触发该事件。在react-router中也采用了手动触发hashchange事件的方式。
var listenerCount = 0;
function checkDOMListeners(delta) {
listenerCount += delta;
if (listenerCount === 1 && delta === 1) {
window.addEventListener(HashChangeEvent$1, handleHashChange);
} else if (listenerCount === 0) {
window.removeEventListener(HashChangeEvent$1, handleHashChange);
}
}
2、Router:是根据当前的url来渲染相对应的component,所以在这里它调用了history监听url改变的listen函数
if (!props.staticContext) {
_this.unlisten = props.history.listen(function (location) {
if (_this._isMounted) {
_this.setState({
location: location
});
} else {
_this._pendingLocation = location;
}
});
}
listen函数如下所示,该函数最终返回的结果是一个移除监听的函数。其中checkDOMListeners()函数的实现见上图。
function listen(listener) {
var unlisten = transitionManager.appendListener(listener);
checkDOMListeners(1);
return function () {
checkDOMListeners(-1);
unlisten();
};
}
3、Route 组件:的主要作用就是根据匹配结果来决定是否渲染某个component。它会根据props.match来决定 渲染的component。
return React.createElement(context.Provider, {
value: props
}, children && !isEmptyChildren(children) ? children : props.match ? component ? React.createElement(component, props) : render ? render(props) : null : null);
其中,上图代码段中的props.match是由matchPath(location.pathname, _this.props)计算得出的。
可能暂时挖掘的信息不够完善,后续再继续补充。
更多推荐
所有评论(0)