在 Apollo Client 中手动清理缓存。
示例代码:
import { ApolloProvider, ApolloClient, InMemoryCache } from "@apollo/client";
import { useMemo } from "react";
import { useRouter } from "next/router";
let apolloClient;
function createApolloClient() {
return new ApolloClient({
ssrMode: typeof window === "undefined",
uri: "http://localhost:4000/graphql",
cache: new InMemoryCache(),
});
}
export function useApollo() {
const router = useRouter();
const client = useMemo(() => {
if (!apolloClient) {
apolloClient = createApolloClient();
}
return apolloClient;
}, []);
// 每次路由切换前清空缓存
router.beforePopState(() => {
apolloClient.resetStore();
return true;
});
return client;
}
export function WrapWithApollo({ children }) {
const client = useApollo();
return {children} ;
}
在上述示例中,我们使用了 useMemo 来保证仅在客户端第一次访问时才创建 Apollo Client 实例,从而避免内存泄漏的问题。
同时,我们在路由切换前手动清空缓存,以避免缓存过多而导致内存泄漏。