场景:由于页面没有太多交互功能,只是静态数据的展示,所以希望页面缓存,在返回此页面时,不频繁发送请求。
方法:
1.安装umi-plugin-keep-alive插件和react-activation插件(我在这里用的是pnpm add,用npm install也都可以):
pnpm add umi-plugin-keep-alive --save;
pnpm add react-activation;
2.需要在.umirc.ts文件中手动配置开启插件:
plugins: ['umi-plugin-keep-alive'],
注:这个插件名字像上面这样写才生效,起初把这个插件名字写错成了:“@umijs/max-plugin-keep-alive”,是无法使用的。
3.遇到问题:但是只要在使用了useModel的页面,再使用KeepAlive,都会报错:Uncaught TypeError: Cannot read properties of null (reading 'dispatcher')(没有使用useModel的页面,没有报错)。后来在gitHub查到还需要添加一个配置:
src/app.ts中添加如下配置:
import { autoFixContext } from 'react-activation';
import jsxDevRuntime from 'react/jsx-dev-runtime';
import jsxRuntime from 'react/jsx-runtime';
autoFixContext(
[jsxRuntime, 'jsx', 'jsxs', 'jsxDEV'],
[jsxDevRuntime, 'jsx', 'jsxs', 'jsxDEV'],
);
4.然后在组件中使用就不会报错啦:
import { KeepAlive } from '@umijs/max';
export default () => {
return (
<>
<KeepAlive
name="home"
when={() => {
/*根据路由的前进和后退状态去判断页面是否需要缓存,前进时缓存,后退时不缓存(卸载)。 when中的代码是在页面离开(卸载)时触发的。*/
return history.action !== 'POP';
}}
>
<Home />
</KeepAlive>
</>
);
};
以上,就完成了umi4中使用KeepAlive组件的配置啦,如有不足及问题也欢迎联系我~