Created
May 7, 2022 09:18
-
-
Save varHarrie/538f4aec748338ebd31ec6673d96c93a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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