React router cache route實現緩存頁面流程介紹
一、背景
在開發(fā)中,從A頁面跳轉到other頁面,再返回A頁面時react-router會直接刷新頁面,導致A頁面中已加載的海量數據狀態(tài)丟失,需要重新加載,用戶體驗不佳,所以必須將海量數據狀態(tài)進行緩存。
(在小編的實際場景中,A頁面是一堆模型&業(yè)務數據標注點,由于模型永遠不會更改,但是加載又很緩慢,因此,希望從other頁面返回A頁面時,模型不會重新加載,但是需要更新業(yè)務數據。)
(其他應用場景舉例:開發(fā)中有從詳情頁返回列表頁的需求,這樣一來頁面返回后使用react-router會直接刷新頁面,導致頁面中的分頁和搜索條件全部丟失,用戶體驗不佳,所以就必須將列表頁的狀態(tài)進行緩存。)
二、參考方法
網上搜索大概有幾種方法:
1、使用localStorage/sessionStorage進行頁面的狀態(tài)的保存,跳轉頁面后再進行獲取,這種方法雖然可行,但是從根本來說還是從新向后臺再一次請求了數據,不算最佳方案。
2、react-activation,嘗試未果
3、react-kepper,需要將項目的react-router替換掉,風險較大,慎用
4、react-router-cache-route,簡單易用,最佳方案
三、react-router-cache-route的使用
就是把Switch替換成CacheSwitch,因為因為Switch組件只保留第一個匹配狀態(tài)的路由,卸載掉其他路由
把Route替換成CacheRoute
注意:other面回退A頁面時使用this.props.history.push(‘’路徑’)可以實現頁面的緩存
但當使用this.props.history.go(-1)則緩存失敗
四、具體步驟
1、替換Switch和Route
靜態(tài)路由
import React,{Component} from 'react'
import { Route} from 'react-router-dom'
import {CacheRoute,CacheSwitch} from 'react-router-cache-route'
import PageA from './demo/PageA.js'
import PageB from './demo/PageB.js'
import PageOther from './demo/PageOther.js'
class App extends Component{
render(){
return(
<div className='App'>
<CacheSwitch>
<CacheRoute exact path='/platform/PageA' component={PageA}/>
<Route path='/platform/PageB' component={PageB}/>
<Route path='/platform/PageOther' component={PageOther}/>
</CacheSwitch>
</div>
)
}
}
export default App;
動態(tài)路由
function AppRouter() {
return (
<Router history={history}>
<AppContainer>
<CustomHeader />
<CacheSwitch>
{routes.map((route: RouteType, index: number) => {
return route.cache ? (
<CacheRoute
exact={true}
path={`/${route.routerPath}`}
key={index}
component={route.component}
/>
) : (
<Route
// strict={true}
exact={true}
path={`/${route.routerPath}`}
key={index}
component={route.component}
/>
);
})}
<Redirect to="/login" />
</CacheSwitch>
</AppContainer>
</Router>
);
}
動態(tài)理由,加判斷標志位:cache,只有傳遞了cache頁面才能被緩存,沒有傳遞cache,就用普通路由形式
{
path: '/PageA',
component: PageA,
cache:true,//判斷標志位
},
{
path: '/PageB',
component: PageB,
},
2、如何更新其他想要更新的業(yè)務數據
//緩存A頁面跳轉至other頁面()
componentDidCache = () => {
console.log('List cached')
}
//緩存恢復(從other頁面跳轉返回A頁面)
componentDidRecover = () => {
// 這里可以更新業(yè)務數據
console.log('List recovered')
}
3、參考
https://github.com/CJY0208/react-router-cache-route/blob/HEAD/README_CN.md
到此這篇關于React router cache route實現緩存頁面流程介紹的文章就介紹到這了,更多相關React router cache route內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

