使用的是umi-plugin-keep-alive插件,不喜的就可以不用往下看了噢
1. 下载 react-activation 我这里用的是npm,
npm install react-activation
2. 下载umi-plugin-keep-alive
npm install umi-plugin-keep-alive --save
3.在config.js/ts 的defineConfig中手动配置以下代码
plugins: ['umi-plugin-keep-alive']
4,在app.tsx 中引入并输入以下代码
import { autoFixContext } from 'react-activation';
import jsxDevRuntime from 'react/jsx-dev-runtime';
import jsxRuntime from 'react/jsx-runtime';
utoFixContext([jsxRuntime, 'jsx', 'jsxs', 'jsxDev'], [jsxDevRuntime, 'jsx', 'jsxs', 'jsxDev']);
5,此时我们就可以从@umijs/max中引入KeepAlive组件进行使用
因为做的页面级缓存,我们需要在childrenRender属性的函数中使用组件将其返回的ReactNode包裹,同时对部分属性进行解释代码如下:
import {KeepAlive} from '@umijs/max'; //引入
//下面是使用
childrenRender: (children) => {
const { location } = history;
return (
<>
<KeepAlive
name='/About' //可以按照name卸载缓存状态下的<keepalive>节点
id={location.pathname} //唯一标识,缓存多个节点时必须要有
when={() => {
return history.action !== 'POP';
}} //when 为true时缓存,可以是表达式,可以直接是true,可以是函数
>
{/*<About /> */}
{children} //缓存的节点,此处为页面级缓存,也可以在children属性中设置
</KeepAlive>
</>
);
},
(注:这是在umi中做页面级缓存,不做页面级缓存的话,将需要缓存的组件使用组件包裹,属性同)
如果上面的属性没找到你想要的答案,那么可以看看下面几个属性中是否有你需要的东西
saveScrollPosition: boolean | string; 可保存页面的滚动位置autoFreeze: boolean ; 可开启或关闭缓存动画cacheKey: string ;[key: string]: any ;
6.当然不是缓存了就可以的,产品的需求总有一个是需要你去刷新这个被缓存的页面,这时候可以通过useAliveController 来完成这个需求,下面通过带参数跳转路由时刷新页面场景来看一下(其实就是跳转前清除目标页面的缓存)
- 首先第一步引入useAliveController:
import {useAliveController} from '@umijs/max'; - 从useAliveController 声明 dropScope:
const { dropScope } = useAliveController();,接下来就可以使用啦。 - 在跳转前清除目标页面的缓存
const onJumpAggregation = async (record) => {
await dropScope('/aggregation'); // 主要看这行,谢谢,括号中为目标页面path
history.push('/aggregation', {
appPkg: curAppItem.app_pkg,
ctrlId: record.controller_id,
});
};
当然,useAliveController中不止dropScope,这里就简单介绍一下它包含的东西:
getCachingNodes:一个函数,用于获取当前缓存的节点列表。可以用于在需要时手动获取缓存节点并进行进一步处理。dropScope:一个函数,用于删除指定作用域内的缓存。可以用于在需要时手动删除特定缓存。drop:一个函数,用于删除所有缓存。可以用于在需要时手动删除所有缓存。
些方法可以在组件中使用,根据具体需求调用它们来管理组件缓存。
以上是作者所知,如有补充或者错误欢迎指出谢谢