使用umi-plugin-keep-alive实现KeepAlive状态存储,
并且实现
进入下一个页面时缓存,后退页面时不缓存(卸载)
类似微信小程序的页面缓存机制
1、安装
$ npm install umi-plugin-keep-alive --save
//或者
$ yarn add umi-plugin-keep-alive
2、使用
import { KeepAlive, history} from 'umi'
const page = () => {
return (
<>这是一个页面</>
)
}
// 不要直接在上方page组件中包裹KeepAlive,会出问题,要以下面的方式去导出
export default () => {
return (
<KeepAlive
saveScrollPosition="screen" //自动保存共享屏幕容器的滚动位置
id={history.location.search || history.location.pathname} // 根据参数去缓存,如果参数不同就缓存多份,如果参数相同就使用同一个缓存。这样解决了传参改变时,页面不刷新的问题
when={() => { // 根据路由的前进和后退状态去判断页面是否需要缓存,前进时缓存,后退时不缓存(卸载)。 when中的代码是在页面离开(卸载)时触发的。
return history.action != 'POP'; //true卸载时缓存,false卸载时不缓存
}}
>
{/* 页面组件 */}
<page></page>
</KeepAlive>
)
};
更详细的可参考 React Activation
3、和dva组合使用
// 页面
const Home = ()=>{
...
}
// 链接dva
const ModelHome = connect(
({ homeModel }: any) => ({
homeModel
})
)(Home);
// 缓存
export default () => {
return (
<KeepAlive
saveScrollPosition="screen"
id={history.location.search || history.location.pathname}
when={() => {
return history.action != 'POP';
}}
>
{/* 页面组件 */}
<ModelHome></ModelHome>
</KeepAlive>
)
};