1、需求
umi项目首页展示权限模块列表A、B、C。。。,点击模块进入模块详情,详情里可以跳转各种数据列表。问题:1、跳转页面时怎么保存当前页面的滚动高度,使得返回时还能看到跳转前的数据;2、进入A模块,返回,想再次进入A模块,不用重新渲染。
2、调研
经过一番探索,筛选出最符合我需求的、最省事的一个工具:umi-plugin-keep-alive,此功能基于 react-activation实现。所有来自 react-activation 的api都可以由 umi 导出,例如:import {KeepAlive,useActivate, useUnactivate,withActivation,withAliveScope, useAliveController} from 'umi'
3、实现
- 安装
npm install umi-plugin-keep-alive --save
# or
yarn add umi-plugin-keep-alive
- 从
umi中导出KeepAlive,包裹在需要被缓存的组件上
import {connect,KeepAlive} from 'umi';
const Home = props => {
return (
<div className="home">
<KeepAlive>
// 业务代码...
</KeepAlive>
</div>
)
}
export default connect(state => state.homeStore)(Home)
注意:在本地启动,正常展示,代码部署测试线后,首页白屏,或者,接口返回的数据不能映射到组件上,一直loading。尝试将KeepAlive包裹整个组件,如下:
import {connect,KeepAlive} from 'umi';
const Home = props => {
return (
<div className="home">
// 业务代码...
</div>
)
}
const KeepHome = () => (
<KeepAlive>
<Home />
</KeepAlive>
)
export default connect(state => state.homeStore)(KeepHome)
发现Home组件取不到props里的数据和方法。然后尝试将KeepAlive包裹映射store之后的Home组件,如下:
import {connect,KeepAlive} from 'umi';
const Home = props => {
return (
<div className="home">
// 业务代码...
</div>
)
}
const ConnectHome = connect(state => state.homeStore)(Home)
export default () => (
<KeepAlive>
<ConnectHome />
</KeepAlive>
)
发现确实可以。