位置:- 正文

React中使用react-router-cache-route缓存页面状态(react-use)

编辑:rootadmin
React中使用react-router-cache-route缓存页面状态 一、背景

推荐整理分享React中使用react-router-cache-route缓存页面状态(react-use),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:react current,react ir,react_,react_,react_,react it,react-use,react_,内容如对您有帮助,希望把文章链接给更多的朋友!

在开发中,从A页面跳转到other页面,再返回A页面时react-router会直接刷新页面,导致A页面中已加载的海量数据状态丢失,需要重新加载,用户体验不佳,所以必须将海量数据状态进行缓存。 (在小编的实际场景中,A页面是一堆模型&业务数据标注点,由于模型永远不会更改,但是加载又很缓慢,因此,希望从other页面返回A页面时,模型不会重新加载,但是需要更新业务数据。) (其他应用场景举例:开发中有从详情页返回列表页的需求,这样一来页面返回后使用react-router会直接刷新页面,导致页面中的分页和搜索条件全部丢失,用户体验不佳,所以就必须将列表页的状态进行缓存。)

二、参考方法

网上搜索大概有几种方法: 1、使用localStorage/sessionStorage进行页面的状态的保存,跳转页面后再进行获取,这种方法虽然可行,但是从根本来说还是从新向后台再一次请求了数据,不算最佳方案。 2、react-activation,尝试未果 3、react-kepper,需要将项目的react-router替换掉,风险较大,慎用 4、react-router-cache-route,简单易用,最佳方案

三、react-router-cache-route的使用React中使用react-router-cache-route缓存页面状态(react-use)

就是把Switch替换成CacheSwitch,因为因为Switch组件只保留第一个匹配状态的路由,卸载掉其他路由 把Route替换成CacheRoute 注意:other面回退A页面时使用this.props.history.push(‘’路径’)可以实现页面的缓存 但当使用this.props.history.go(-1)则缓存失败

四、具体步骤

1、替换Switch和Route 静态路由

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;

动态路由

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> );}

动态理由,加判断标志位:cache,只有传递了cache页面才能被缓存,没有传递cache,就用普通路由形式

{ path: '/PageA', component: PageA, cache:true,//判断标志位},{ path: '/PageB', component: PageB,},

2、如何更新其他想要更新的业务数据

//缓存A页面跳转至other页面()componentDidCache = () => { console.log('List cached')}//缓存恢复(从other页面跳转返回A页面)componentDidRecover = () => { // 这里可以更新业务数据 console.log('List recovered')}

3、参考 https://github.com/CJY0208/react-router-cache-route/blob/HEAD/README_CN.md

本文链接地址:https://www.jiuchutong.com/zhishi/288875.html 转载请保留说明!
下一篇链接:https://www.jiuchutong.com/zhishi/288876.html
免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

鄂ICP备2023003026号

友情链接: 武汉网站建设 电脑维修 湖南楚通运网络