Skip to content

Instantly share code, notes, and snippets.

@varHarrie
Created May 7, 2022 09:18
Show Gist options
  • Save varHarrie/538f4aec748338ebd31ec6673d96c93a to your computer and use it in GitHub Desktop.
Save varHarrie/538f4aec748338ebd31ec6673d96c93a to your computer and use it in GitHub Desktop.
import { ReactElement, useContext, useRef } from 'react';
import { Freeze } from 'react-freeze';
import { UNSAFE_RouteContext as RouteContext } from 'react-router-dom';
export default function KeepAliveOutlet() {
const caches = useRef<Record<string, ReactElement>>({});
const matchedElement = useContext(RouteContext).outlet; // v6.3之后useOutlet会多了一层嵌套
const matchedPath = matchedElement?.props?.value?.matches?.at(-1)?.pathname as string;
if (matchedElement && matchedPath) {
caches.current[matchedPath] = matchedElement;
}
return (
<>
{Object.entries(caches.current).map(([path, element]) => (
<Freeze key={path} freeze={element !== matchedElement}>
{element}
</Freeze>
))}
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment