React 中自定义实现 Keep Alive 组件

避免在组件卸载和重新挂载时丢失状态。

通过React的上下文(Context)和状态(State)来实现自定义的缓存机制。

  1. 创建缓存上下文:

    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
    import React, { createContext, useContext, useState } from 'react';

    const CacheContext = createContext();

    export const CacheProvider = ({ children }) => {
    const [cache, setCache] = useState({});

    const setCachedComponent = (name, component) => {
    setCache((prevCache) => ({
    ...prevCache,
    [name]: component
    }));
    };

    const getCachedComponent = (name) => {
    return cache[name] || null;
    };

    return (
    <CacheContext.Provider value={{ setCachedComponent, getCachedComponent }}>
    {children}
    </CacheContext.Provider>
    );
    };

    export const useCache = () => useContext(CacheContext);
  2. 使用缓存上下文:

    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
    import React, { useEffect } from 'react';
    import { CacheProvider, useCache } from './CacheContext';

    const MyComponent = () => {
    return <div>这是我的组件</div>;
    };

    const KeepAlive = ({ name, children }) => {
    const { getCachedComponent, setCachedComponent } = useCache();
    const cachedComponent = getCachedComponent(name);

    useEffect(() => {
    if (!cachedComponent) {
    setCachedComponent(name, children);
    }
    }, [cachedComponent, children, name, setCachedComponent]);

    return cachedComponent || children;
    };

    const App = () => {
    return (
    <CacheProvider>
    <KeepAlive name="myComponent">
    <MyComponent />
    </KeepAlive>
    </CacheProvider>
    );
    };

    export default App;