前言
發(fā)現(xiàn)react-route
用Link
或Push
跳轉(zhuǎn)時(shí),沒(méi)有刷新頁(yè)面,但是Url
變了,而且點(diǎn)擊瀏覽器自動(dòng)的返回按鈕鲸鹦,Url
變了但是頁(yè)面不刷新慧库,怎么做到的呢?于是本妹子就從這個(gè)方向研究了下react-route
的源碼馋嗜,給小伙伴們分享下齐板。
解密-點(diǎn)擊返回按鈕但頁(yè)面不刷新
一、HashRouter 分析
通過(guò)location.hash
來(lái)達(dá)到url
變但頁(yè)面不刷新
location.hash=hash
然后在通過(guò)onhashchange
監(jiān)聽(tīng)瀏覽器的返回事件
window.addEventListener('onhashchange', (event) => {
changeDisplayName();//替換顯示的內(nèi)容
});
二葛菇、 BrowserRouter 分析
通過(guò)pushState來(lái)達(dá)到url變但頁(yè)面不刷新甘磨,history.push
實(shí)際是用原生history.pushState
來(lái)實(shí)現(xiàn)的,history.replace
實(shí)際是用原生history.replaceState
來(lái)實(shí)現(xiàn)的眯停。
changeDisplayName();//替換顯示的內(nèi)容
window.history.pushState(null, null, newUrl);
然后在通過(guò)popstate
監(jiān)聽(tīng)瀏覽器的返回事件
window.addEventListener('popstate', (event) => {
changeDisplayName();//替換顯示的內(nèi)容
});
案例
具體代碼為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 結(jié)合
popstate
和onhashchange
方法對(duì)android4.4.4
不兼容,需要引入history這個(gè)npm
包莺债,里面有兼容性代碼滋觉,如果判斷不兼容,就直接按照window.location.href
跳轉(zhuǎn)齐邦。
具體代碼為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'),
)
四椎侠、查看顯示頁(yè)面
源碼
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
對(duì)象接受一個(gè)名為 displayName
的property
,類型為字符串措拇。React DevTools
使用該字符串來(lái)標(biāo)示context
要顯示的內(nèi)容我纪。
示例,下述組件在 DevTools
中將顯示為 MyDisplayName:
const MyContext = React.createContext(/* some value */);
MyContext.displayName = 'MyDisplayName';
<MyContext.Provider> // "MyDisplayName.Provider" 在 DevTools 中
<MyContext.Consumer> // "MyDisplayName.Consumer" 在 DevTools 中
Happy coding .. :)