React Router源码分析

前言

发现react-routeLinkPush跳转时,没有刷新页面,但是Url变了,而且点击浏览器自动的返回按钮,Url变了但是页面不刷新,怎么做到的呢?于是本妹子就从这个方向研究了下react-route的源码,给小伙伴们分享下。

解密-点击返回按钮但页面不刷新

一、HashRouter 分析

通过location.hash来达到url变但页面不刷新

location.hash=hash

然后在通过onhashchange监听浏览器的返回事件

window.addEventListener('onhashchange', (event) => {
    changeDisplayName();//替换显示的内容
});

二、 BrowserRouter 分析

通过pushState来达到url变但页面不刷新,history.push实际是用原生history.pushState来实现的,history.replace实际是用原生history.replaceState来实现的。

changeDisplayName();//替换显示的内容
window.history.pushState(null, null, newUrl);

然后在通过popstate监听浏览器的返回事件

window.addEventListener('popstate', (event) => {
    changeDisplayName();//替换显示的内容
});
案例

具体代码为codepen上的change page with history package

import React, { useEffect, useState, useRef, Component } from 'react';
const MapPage=()=>{
  return 
MapPage
} const RankPage=()=>{ return
RankPage
} function ConPage() { const[Page, setPage] = useState('rank'); useEffect(()=>{ window.addEventListener('popstate', (event) => { console.log("location: " + document.location + ", state: " + JSON.stringify(event.page)); let val; if(event.page=='rank') { val='rank' }else{ val='map' } console.log('useEffect',val) setPage(val) }); },[]) const _changePage = () => { if(Page=='rank') { setPage('map') window.history.pushState({page:'map'}, null, 'http://dev.jd.com:10086/con?pId=map'); }else{ setPage('rank') window.history.pushState({page:'rank'}, null, 'http://dev.jd.com:10086/con?pId=rank'); } } return (
切换路由
{Page=='rank' && } {Page=='map' && }
) } export default ConPage

三、与 history 结合

popstateonhashchange方法对android4.4.4不兼容,需要引入history这个npm包,里面有兼容性代码,如果判断不兼容,就直接按照window.location.href跳转。

具体代码为codepen上的change URL with history package

const history = History.createBrowserHistory();
const Location = history.location;

const MapPage=()=>{
  return 
MapPage
} const RankPage=()=>{ return
RankPage
} function ConPage() { const[Page, setPage] = React.useState('rank'); React.useEffect(()=>{ history.listen((Location, action) => { console.log(action, Location.state); if(Location.state.page && Location.state.page=='map'){ setPage('map') }else{ setPage('rank') } }); },[]) const _changePage = () => { if(Page=='rank') { history.push('/con?pId=map',{ page: 'map' }); }else{ history.push('/con?pId=rank',{ page: 'rank' }); } } return (
{Page=='rank' &&} {Page=='map' &&}
) } ReactDOM.render( , document.getElementById('root'), )

四、查看显示页面

源码

react-router里的RouterContext.js

//TODO:直接用React.createContext也可以
import createContext from "mini-create-react-context";

const createNamedContext = name => {
  const context = createContext();
  context.displayName = name;

  return context;
};

const context = /*#__PURE__*/ createNamedContext("Router");
export default context;
分析

Context.displayName解释:
context 对象接受一个名为 displayName property,类型为字符串。React DevTools 使用该字符串来标示context 要显示的内容。

示例,下述组件在 DevTools 中将显示为 MyDisplayName

const MyContext = React.createContext(/* some value */);
MyContext.displayName = 'MyDisplayName';

 // "MyDisplayName.Provider" 在 DevTools 中
 // "MyDisplayName.Consumer" 在 DevTools 中

Happy coding .. :)

相关链接

博客原文

react-router github

history github

popstate接口API

onHashchange兼容性

change URL with history package

Change URL without refreshing page

你可能感兴趣的:(react-router)