import React, {useLayoutEffect, useRef, useState} from "react"; import {decodeKeepAliveMeta, iKeepAliveMeta} from "./utils/keepalive.utils"; import {KeepAliveCacheItemWrapper} from "./KeepAliveCacheItemWrapper"; /** * 初始化 * useLayoutEffect start * useEffect start * * 销毁 * useLayoutEffect end * useLayoutEffect start * useEffect end * useEffect start * @author 韦胜健 * * findDomNode * 如果children是一个普通文本,则得到的是#text对象 * 如果children是多个dom节点,得到的是第一个dom节点 * @date 2023.6.3 12:27 */ export const KeepAlive: React.FC<{ children: any, onInit?: (meta: iKeepAliveMeta) => void, isCache?: (meta: iKeepAliveMeta) => boolean, onBeforeUnmount?: () => void, }> = (props) => { const [count, forceUpdate] = useState(0); const cacheList = useRef([] as iKeepAliveMeta[]); let activeIndex = -1; const decodeMeta = decodeKeepAliveMeta(props.children); if (decodeMeta != null) { const cacheIndex = cacheList.current.findIndex(({ key, type }) => (key === decodeMeta.key && decodeMeta.type === type)); if (cacheIndex === -1) { cacheList.current.push(decodeMeta); activeIndex = cacheList.current.length - 1; props.onInit?.(decodeMeta); } else { activeIndex = cacheIndex; cacheList.current[cacheIndex].children = props.children; } } /** * 当某个缓存要销毁的时候,不在本次渲染的时候销毁这个实例; * 而是在下一次事件循环的时候销毁这个实例,避免导致实例由于销毁导致的闪烁问题 * @author 韦胜健 * @date 2023/6/7 10:22 */ const excludeList = !props.isCache ? [] : cacheList.current.filter((i, index) => (index !== activeIndex && !props.isCache!(i))); if (!!excludeList.length) { setTimeout(() => { cacheList.current = cacheList.current.filter(i => excludeList.indexOf(i) === -1); forceUpdate(count + 1); }, 0); } useLayoutEffect(() => { return () => { props.onBeforeUnmount?.(); }; }, []); return ( <>{ cacheList.current.map((i, index) => ( {i.children} )) } ); }; export default KeepAlive;