|
|
|
@@ -4,39 +4,55 @@ |
|
|
|
* @Description: 页面状态缓存,pop 回到这个页面的时候,重新构建之前的状态 |
|
|
|
*/ |
|
|
|
|
|
|
|
const pageKeys: string[] = []; |
|
|
|
import { useCallback, useState } from 'react'; |
|
|
|
|
|
|
|
export const useCacheState = () => { |
|
|
|
const { pathname } = window.location; |
|
|
|
const key = 'pagecache:' + pathname; |
|
|
|
const pageKeys: string[] = []; |
|
|
|
// let stateCaches: Record<string, any> = {}; |
|
|
|
|
|
|
|
const getState = () => { |
|
|
|
const jsonStr = sessionStorage.getItem(key); |
|
|
|
if (jsonStr) { |
|
|
|
removeState(); |
|
|
|
// 获取页面缓存 |
|
|
|
const getCacheState = (key: string) => { |
|
|
|
const jsonStr = sessionStorage.getItem(key); |
|
|
|
if (jsonStr) { |
|
|
|
removeCacheState(key); |
|
|
|
try { |
|
|
|
return JSON.parse(jsonStr); |
|
|
|
} catch (error) { |
|
|
|
return undefined; |
|
|
|
} |
|
|
|
return undefined; |
|
|
|
}; |
|
|
|
|
|
|
|
const setState = (state: any) => { |
|
|
|
pageKeys.push(key); |
|
|
|
sessionStorage.setItem(key, JSON.stringify(state)); |
|
|
|
}; |
|
|
|
|
|
|
|
const removeState = () => { |
|
|
|
sessionStorage.removeItem(key); |
|
|
|
const index = pageKeys.indexOf(key); |
|
|
|
if (index !== -1) { |
|
|
|
pageKeys.splice(index, 1); |
|
|
|
} |
|
|
|
}; |
|
|
|
} |
|
|
|
return undefined; |
|
|
|
}; |
|
|
|
|
|
|
|
return [getState(), setState] as const; |
|
|
|
// 移除页面 state 缓存 |
|
|
|
const removeCacheState = (key: string) => { |
|
|
|
sessionStorage.removeItem(key); |
|
|
|
const index = pageKeys.indexOf(key); |
|
|
|
if (index !== -1) { |
|
|
|
pageKeys.splice(index, 1); |
|
|
|
} |
|
|
|
}; |
|
|
|
|
|
|
|
// 移除所有页面 state 缓存 |
|
|
|
export const removeAllPageCacheState = () => { |
|
|
|
pageKeys.forEach((key) => { |
|
|
|
sessionStorage.removeItem(key); |
|
|
|
}); |
|
|
|
}; |
|
|
|
|
|
|
|
export const useCacheState = () => { |
|
|
|
const { pathname } = window.location; |
|
|
|
const key = 'pagecache:' + pathname; |
|
|
|
|
|
|
|
const setCacheState = useCallback( |
|
|
|
(state: any) => { |
|
|
|
if (state) { |
|
|
|
pageKeys.push(key); |
|
|
|
sessionStorage.setItem(key, JSON.stringify(state)); |
|
|
|
} |
|
|
|
}, |
|
|
|
[key], |
|
|
|
); |
|
|
|
|
|
|
|
const [cacheState] = useState(() => getCacheState(key)); |
|
|
|
return [cacheState, setCacheState] as const; |
|
|
|
}; |