该问题的解决方法是通过自定义一个缓存配置函数来解决。具体步骤如下:
ApolloClient
中。import { InMemoryCache, defaultDataIdFromObject } from '@apollo/client';
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
posts: {
keyArgs: false,
merge(existing = [], incoming, { args: { after } }) {
return after ? [...existing, ...incoming] : incoming;
},
read(existing, { args: { after = null, first = 5 } }) {
if (!after) {
return existing && existing.slice(0, first);
}
const index = existing.findIndex((item) => item.cursor === after);
return existing && existing.slice(index + 1, index + 1 + first);
},
},
},
},
},
dataIdFromObject: (object) => {
switch (object.__typename) {
case 'Post':
return object.id;
default:
return defaultDataIdFromObject(object);
}
},
});
const client = new ApolloClient({
uri: 'http://localhost:4000/graphql',
cache,
});
import { gql, useQuery } from '@apollo/client';
const POSTS_QUERY = gql`
query PostQuery($first: Int!, $after: String) {
posts(first: $first, after: $after) @connection(key: "posts") @relayStylePagination {
edges {
node {
id
title
body
}
cursor
}
}
}
`;
function Posts() {
const { data, fetchMore } = useQuery(POSTS_QUERY, {
variables: { first: 1, after: null },
});
const { edges, pageInfo } = data.posts || {};
const loadMore = () => {
fetchMore({
variables: { first: 1, after: pageInfo.endCursor },
});
};