Scenario: Since the page does not have many interactive functions and is just a display of static data, it is hoped that the page will be cached and requests will not be sent frequently when returning to this page.
method:
1. Install the umi-plugin-keep-alive plug-in and react-activation plug-in (I use pnpm add here, you can also use npm install):
pnpm add umi-plugin-keep-alive --save;
pnpm add react-activation;
2. You need to manually configure and enable the plug-in in the .umirc.ts file:
plugins: ['umi-plugin-keep-alive'],
Note: This plug-in name only takes effect if it is written as above. At first, the plug-in name was wrongly written as: "@umijs/max-plugin-keep-alive", which cannot be used.
3. Encounter a problem: But as long as you use KeepAlive on a page that uses useModel, an error will be reported: Uncaught TypeError: Cannot read properties of null (reading 'dispatcher') (no error will be reported for pages that do not use useModel). Later, I found on gitHub that I still need to add a configuration:
Add the following configuration to 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. Then use it in the component and no error will be reported:
import { KeepAlive } from '@umijs/max';
export default () => {
return (
<>
<KeepAlive
name="home"
when={() => {
/*根据路由的前进和后退状态去判断页面是否需要缓存,前进时缓存,后退时不缓存(卸载)。 when中的代码是在页面离开(卸载)时触发的。*/
return history.action !== 'POP';
}}
>
<Home />
</KeepAlive>
</>
);
};
The above completes the configuration of using the KeepAlive component in umi4. If you have any deficiencies or questions, please feel free to contact me~