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 <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

三、與 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 <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'),
  )

四、查看顯示頁面

源碼

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對象接受一個名為 displayNameproperty,類型為字符串。React DevTools使用該字符串來標示context 要顯示的內容。

示例,下述組件在 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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。