React Router源码分析

前言

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

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

1、HashRouter 分析

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

location.hash=hash
复制代码

而后在经过onhashchange监听浏览器的返回事件android

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

2、 BrowserRouter 分析

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

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

而后在经过popstate监听浏览器的返回事件github

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

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

import React, { useEffect, useState, useRef, Component } from 'react';
const MapPage=()=>{
  return <div>MapPage</div>
}
const RankPage=()=>{
  return <div>RankPage</div>
}

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 (
    <div> <div onClick={_changePage} className='btnTest'> 切换路由</div> {Page=='rank' && <RankPage /> } {Page=='map' && <MapPage /> } </div>
  )
}
export default ConPage
复制代码

3、与 history 结合

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

具体代码为codepen上的change URL with history packagereact-router

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

const MapPage=()=>{
  return <div>MapPage</div>
}
const RankPage=()=>{
  return <div>RankPage</div>
} 

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 (
    <div> <button onClick={_changePage} className='btnTest'> 切换路由</button> {Page=='rank' &&<RankPage />} {Page=='map' &&<MapPage />} </div>
  )
}

ReactDOM.render(
<ConPage />, document.getElementById('root'), ) 复制代码

4、查看显示页面

源码

react-router里的RouterContext.jsapp

//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对象接受一个名为 displayNameproperty,类型为字符串。React DevTools使用该字符串来标示context 要显示的内容。ide

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

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

<MyContext.Provider> // "MyDisplayName.Provider" 在 DevTools 中
<MyContext.Consumer> // "MyDisplayName.Consumer" 在 DevTools 中
复制代码

Happy coding .. :)

相关连接

博客原文

react-router github

history github

popstate接口API

onHashchange兼容性

change URL with history package

Change URL without refreshing page

相关文章
相关标签/搜索