react页⾯缓存插件react-router-cache-router
react router v5主要业务场景就是列表页跳转到详情页中,再回到列表页中,列表页还是保持之前的状态⽐如:分页,搜索条件
⽹上搜索⼤概有⼏种⽅法:
1. 使⽤localStorage/sessionStorage进⾏页⾯的状态的保存,跳转页⾯后再进⾏获取,这种⽅法虽然可⾏,但是从根本来说还是从新向后台再⼀次请求了数据,不算最佳⽅案。
2. react-kepper,需要将项⽬的react-router替换掉,风险较⼤,慎⽤
3. react-router-cache-route,简单易⽤,最佳⽅案
最后采⽤的第三种
基本使⽤⽅法:
就是把Switch替换成CacheSwitch,因为因为Switch组件只保留第⼀个匹配状态的路由,卸载掉其他路由把Route替换成CacheRoute
注意:详情页⾯回退列表页时使⽤this.props.history.push('路径')可以实现页⾯的缓存
但当使⽤this.(-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>
)}
/>