前言
發現react-route
用Link
或Push
跳轉時,沒有刷新頁面,但是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 結合
popstate
和onhashchange
方法對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
對象接受一個名為 displayName
的property
,類型為字符串。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 .. :)