首页 > 系统服务 > 详细

react页面缓存插件 react-router-cache-router

时间:2021-09-03 23:58:32      阅读:25      评论:0      收藏:0      [点我收藏+]

主要业务场景就是列表页跳转到详情页中,再回到列表页中,列表页还是保持之前的状态 比如:分页,搜索条件

网上搜索大概有几种方法:
 1. 使用localStorage/sessionStorage进行页面的状态的保存,跳转页面后再进行获取,这种方法虽然可行,但是从根本来说还是从新向后台再一次请求了数据,不算最佳方案。
 2. react-kepper,需要将项目的react-router替换掉,风险较大,慎用
 3. react-router-cache-route,简单易用,最佳方案
最后采用的第三种
基本使用方法:
就是把Switch替换成CacheSwitch,因为因为Switch组件只保留第一个匹配状态的路由,卸载掉其他路由把Route替换成CacheRoute
注意:详情页面回退列表页时使用this.props.history.push(‘路径‘)可以实现页面的缓存
但当使用this.props.history.go(-1)则有可能缓存失败
1. 安装
npm install react-router-cache-route --save  /    yarn add react-router-cache-route
2. 引入
import CacheRoute, { CacheSwitch } from ‘react-router-cache-route‘
3. 示例
 const App = () => (
      <Router>
        <CacheSwitch>
          <CacheRoute exact path="/list" component={List} />
          <Route exact path="/item/:id" component={Item} />
          <Route render={() => <div>404 Not Found</div>} />
        </CacheSwitch>
      </Router>
    )
4. 注意
//解决缓存页面中的bug (菜单异常)  会出现监听不到路由
//给CacheRoute增加属性when 属性值为true false 
//配置路由demo.js文件中 
{ client_type: 2, name: ‘设备管理‘, path: ‘/web/monitor/device‘, cacheRoute: true, applyRouteName:[‘/web/monitor/device2/readDevice‘] }
//增加applyRouteName属性 值为:这个路由中的子路由地址
const whenFunction = (applyRouteName) => {
     return () => applyRouteName!==undefined && applyRouteName.includes(window.location.pathname)
}

<CacheRoute path={item.path} key={item.path} cacheKey={"MyComponent"} exact when={whenFunction(item.applyRouteName)} render={route => ( <BaseView key={idx} {...route} handleHeader={handleHeader} handleSlider={handleSlider} listenRouterPath={listenRouterPath} > <Components {...route} /> </BaseView> )} />

 

react页面缓存插件 react-router-cache-router

原文:https://www.cnblogs.com/shine1234/p/15222336.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!