import React from 'react';
|
import { useLocation } from 'react-router-dom';
|
import KeepAlive, { useAliveController } from 'react-activation';
|
|
// 不需要缓存的路径
|
const EXCLUDED_PATHS = ['/', '/login'];
|
|
/**
|
* 判断是否为子路径(详情/编辑/创建页面)
|
* 匹配模式: /resource/123/show, /resource/123/edit, /resource/123, /resource/create
|
*/
|
const isSubPath = (path) => {
|
if (!path) return false;
|
const patterns = [
|
/^\/[^/]+\/\d+\/(show|edit)$/, // /task/123/show 或 /task/123/edit
|
/^\/[^/]+\/\d+$/, // /task/123
|
/^\/[^/]+\/create$/, // /task/create
|
];
|
return patterns.some(pattern => pattern.test(path));
|
};
|
|
/**
|
* KeepAlive 包装组件
|
* 根据当前路由路径缓存页面组件,切换 Tab 时保持页面状态
|
* 注意:子路径(详情/编辑/创建页面)不进行缓存
|
*/
|
const KeepAliveWrapper = ({ children }) => {
|
const location = useLocation();
|
const { drop, getCachingNodes } = useAliveController();
|
|
// 检查是否应该缓存当前路径
|
// 排除:登录页、根路径、子路径(详情/编辑/创建页面)
|
const shouldCache = !EXCLUDED_PATHS.includes(location.pathname) && !isSubPath(location.pathname);
|
|
// 暴露 drop 方法给 TabsBar 使用
|
React.useEffect(() => {
|
// 将 drop 方法挂载到 window,供 TabsBar 调用
|
window.__keepAliveController = {
|
drop,
|
getCachingNodes
|
};
|
return () => {
|
delete window.__keepAliveController;
|
};
|
}, [drop, getCachingNodes]);
|
|
if (!shouldCache) {
|
return children;
|
}
|
|
return (
|
<KeepAlive
|
id={location.pathname}
|
name={location.pathname}
|
cacheKey={location.pathname}
|
>
|
{children}
|
</KeepAlive>
|
);
|
};
|
|
export default KeepAliveWrapper;
|