zhou zhou
9 小时以前 4220dbfd495b2ec179c5d7f22531f3bbd80b2525
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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;