react-keepalive-router实现路由缓存方案
项目背景:react项目使用Route进行路由切换,需求是不同的路由切换后,页面进行缓存,重新切换页面之后,使用缓存的页面不再重新请求接口数据
原本实现:原来没有实现路由缓存,然后实现了操作页面dom进行display:none来进行页面隐藏,实现上述要求
优化:使用react-keepalive-router实现路由改造
1.首先实现一下通过react-keepalive-router进行路由缓存优化
实现原理:
初始化:选择该页面,读取页面内容
切换页面:将当前页面存入缓存,查看当前页面是否在缓存中,是的话直接读取缓存,否的话打开新页面
销毁页面:当缓存进行清除
实现过程:
(1)安装
npm install react-keepalive-router --save
(2)缓存域
import { KeepaliveRouterSwitch, KeepaliveRoute, addKeeperListener } from 'react-keepalive-router'
<KeepaliveRouterSwitch>
<KeepaliveRoute exact path='/' render={() => <Redirect to='/dashboard' />} />
{routes.map(
({ isKeepDisabled = false, path, ...dynamics }, key) => {
return <KeepaliveRoute shouldKeep={shouldKeep} key={key} exact path={path} component={dynamic({ app, ...dynamics })} />
}
)}
</KeepaliveRouterSwitch>
(3)清除缓存
cacheDispatch({ type:'reset' })
cacheDispatch({ type:'reset',payload:'cacheId' })
cacheDispatch({ type:'reset',payload:['cacheId1','cacheId2'] })
其实本质上也是实现dom的隐藏与显示
2.使用dom显示与隐藏来进行路由缓存
通过包装keepRoute,在其上实现路由问题
<Route exact path='/' render={() => <Redirect to='/dashboard' />} />
{routes.map(
({ isKeepDisabled = false, path, ...dynamics }, key) => {
const Component = isKeepDisabled ? Route : KeepRoute;
return <Component shouldKeep={shouldKeep} key={key} exact path={path} component={dynamic({ app, ...dynamics })} />
}
)}
const KeepRoute = withRouter(keep(Route)) render() { const { matched, pageRoot } = this.state; return matched ? <div className={this.props.path} ref={this.savePageRoot} style={{ height: '100%' }}> <KeepContext.Provider value={{ matched, pageRoot, onPageShow: this.onPageShow, onPageHide: this.onPageHide }}> {<Route {...this.props} />} </KeepContext.Provider> </div> : null }
参考文档:https://juejin.cn/post/6922340460136513549(强推,写的很好)
浙公网安备 33010602011771号