• react实现keepAlive 可手动清除缓存的


     vue自带keepAlive功能这个大家都知道,但是如果是react呢?

     react功能特别单一的,只维护视图和数据渲染同步部分,其余的依赖三方包。

    今天讲的内容与第三方包reat-activation有关

     封装

    1. import React, { useEffect } from 'react';
    2. import KeepAlive, { useAliveController } from 'react-activation';
    3. import type { FC } from 'react';
    4. interface Iprops {
    5. name: string;
    6. }
    7. const ChildDemo: FC<Iprops> = props => {
    8. const keepAliveKey = props.name;
    9. if (!keepAliveKey) {
    10. console.error('keepAlive 包装组件 的key不能为空');
    11. }
    12. const { dropScope } = useAliveController();
    13. // 关闭页签时清空缓存
    14. const clearCache = (e: any) => {
    15. console.log('关闭tab', e?.data?.deleteTab, keepAliveKey);
    16. if (e?.data?.deleteTab === keepAliveKey) {
    17. dropScope(keepAliveKey);
    18. }
    19. };
    20. //接受关闭当前页面的事件,这是特定项目的事件,请根据自己的项目来处理
    21. useEffect(() => {
    22. //这里是项目的api,其他地方未必会是这样
    23. window.addEventListener('message', clearCache, false);
    24. return () => {
    25. //页面销毁的时候,清空事件监听
    26. window.removeEventListener('message', clearCache, false);
    27. };
    28. }, []);
    29. return <div />;
    30. };
    31. /**
    32. * @param key 页面组件的文件路径 例如:'/baidu/something/doing'
    33. * @param children 要被包装的React页面组件
    34. * @returns
    35. */
    36. const KeepAliveBoundarie: FC<Iprops> = props => {
    37. const keepAliveKey = props.name;
    38. return (
    39. <KeepAlive name={keepAliveKey}>
    40. {props.children}
    41. <ChildDemo name={keepAliveKey} />
    42. </KeepAlive>
    43. );
    44. };
    45. export default KeepAliveBoundarie;

    使用:

    1. import React from 'react';
    2. import { XpKeepAlive } from '@/components';
    3. import Demo from './kIndex';
    4. export default () => {
    5. return (
    6. <XpKeepAlive name='这里最好填写页面对应的路由路径,避免出现重复'>
    7. <Demo />
    8. </XpKeepAlive>
    9. );
    10. };

    注意:

            react-activation和react的context有一定的关系,如果你需要把缓存的功能抽到npm包时候,切记一定要保证npm里面的react版本和你的程序的react版本一样。

            可以选择配置npm里面的react以你的项目的react版本为主(参考webpack externals),否则会出现两个react程序的情况,这样缓存由npm包里面的react维护,和你的主程序是隔离的。

    作者对这个问题的回复链接

  • 相关阅读:
    ZFS了解
    上市公司股息红利差别化个人所得税政策
    whisper+剪映+chatgpt实现实时语音对话功能
    Git 开源的版本控制系统-04-branch manage 分支管理
    Leetcode290. 单词规律
    ManGe Commander 文档 v0.2
    C语言典型例题28
    鲸探发布点评:9月20日发售FPX戒指、中山大学号科考船数字藏品
    python和go相互调用的两种方法
    【java8新特性】02:常见的函数式接口
  • 原文地址:https://blog.csdn.net/u014071104/article/details/126761613