You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

useCacheState.ts 1.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * @Author: 赵伟
  3. * @Date: 2024-04-28 11:49:48
  4. * @Description: 页面状态缓存,pop 回到这个页面的时候,重新构建之前的状态
  5. */
  6. import { parseJsonText } from '@/utils';
  7. import { useCallback, useState } from 'react';
  8. const pageKeys: string[] = [];
  9. // let stateCaches: Record<string, any> = {};
  10. // 获取页面缓存
  11. const getCacheState = (key: string) => {
  12. const jsonStr = sessionStorage.getItem(key);
  13. if (jsonStr) {
  14. removeCacheState(key);
  15. return parseJsonText(jsonStr);
  16. }
  17. return undefined;
  18. };
  19. // 移除页面 state 缓存
  20. const removeCacheState = (key: string) => {
  21. sessionStorage.removeItem(key);
  22. const index = pageKeys.indexOf(key);
  23. if (index !== -1) {
  24. pageKeys.splice(index, 1);
  25. }
  26. };
  27. /**
  28. * 移除所有页面 state 缓存
  29. */
  30. export const removeAllPageCacheState = () => {
  31. pageKeys.forEach((key) => {
  32. sessionStorage.removeItem(key);
  33. });
  34. };
  35. /**
  36. * 缓存页面数据
  37. */
  38. export const useCacheState = () => {
  39. const { pathname } = window.location;
  40. const key = 'pagecache:' + pathname;
  41. const setCacheState = useCallback(
  42. (state?: any) => {
  43. if (state) {
  44. pageKeys.push(key);
  45. sessionStorage.setItem(key, JSON.stringify(state));
  46. }
  47. },
  48. [key],
  49. );
  50. const [cacheState] = useState(() => getCacheState(key));
  51. return [cacheState, setCacheState] as const;
  52. };