1、安装
yarn add react-activation react-router-config
2、路由懒加载
import { lazy } from "react";
{
path: "/page",
title: "page",
expect: true,
component: lazy(() => import("./pages/page.jsx")), //懒加载写法
},
3、全局引入,可以在入口文件main处引入,并使用
import { AliveScope } from "react-activation";
ReactDOM.render(
<AliveScope>
<App />
</AliveScope>
document.getElementById("root")
);
4、使用路由配置的数组进行替换,后面一篇文章就是如何使用react-router-config进行react路由配置,这里只演示关键代码,具体部分根据业务逻辑适配
import KeepAlive from "react-activation";
import { renderRoutes } from "react-router-config"
//核心部分-包裹路由组件
const Component = route.component;
return {
...route,
component: (props) => (
<KeepAlive name={route.path}> //这里的name,我定义的是路由path,方便需要卸载路由的使用直接使用这个path卸载就行
<Component {...props} />
</KeepAlive>
),
};
//核心部分-渲染路由
{renderRoutes(routes)}
5、卸载某个页面的缓存
import { useAliveController } from "react-activation";
const { drop, dropScope, clear, getCachingNodes } = useAliveController();
//核心代码
drop(path) //路由的path,就可以自动卸载路由的缓存,让具体缓存失效
注:经过上面的配置,就可以简单迅速的实现懒加载及路由缓存的结合使用了
浙公网安备 33010602011771号