在Next.js的_router.js_文件中添加一个_onPrefetch_钩子来手动触发查询,以避免不必要的重新获取数据。以下是示例代码:
// pages/_app.js
import { ApolloProvider } from '@apollo/client';
import { useApollo } from '../lib/apolloClient';
function MyApp({ Component, pageProps }) {
const apolloClient = useApollo(pageProps.initialApolloState);
return (
);
}
export default MyApp;
// pages/index.js
import { useQuery } from '@apollo/client';
import gql from 'graphql-tag';
import Link from 'next/link';
import { useState } from 'react';
import { useRouter } from 'next/router';
const QUERY = gql`
query Posts($first: Int!, $skip: Int!) {
allPosts(first: $first, skip: $skip) {
id
title
}
}
`;
const Index = () => {
const [showing, setShowing] = useState(5);
const { data, loading, error } = useQuery(QUERY, {
variables: { first: showing, skip: 0 },
notifyOnNetworkStatusChange: true,
});
const router = useRouter();
const handleShowMore = () => {
setShowing(showing + 5);
router.push('/'); // <-- 需要手动触发查询 useEffect(() => { refetch() }, [])
}
if (error) return Error: {JSON.stringify(error)};
if (loading) return Loading...;
return (
{data.allPosts.map((post) => (
{post.title}
))}
);
};
export default Index;
// lib/apolloClient.js
import { useMemo } from 'react';
import {
ApolloClient,
HttpLink,
InMemoryCache,
NormalizedCacheObject
} from '@apollo/client';
let apolloClient;
function createApolloClient() {
return new ApolloClient({
ssrMode: typeof window === 'undefined',
link: new HttpLink({
uri: 'http://localhost:3000/graphql',
credentials: 'same-origin',
}),
cache: new InMemoryCache(),
});
}
export function initializeApollo(initialState = null) {
const _apolloClient = apolloClient ?? createApolloClient();
if (initial