使用fetchMore方法时,可以通过在options对象中使用fetchPolicy: 'cache-and-network'来避免重复的网络请求。同时,可以使用updateQuery函数在缓存中更新数据。
示例代码:
import { useQuery } from '@apollo/client';
import { GET_POSTS } from './queries';
const Posts = () => {
  const { data, loading, fetchMore } = useQuery(GET_POSTS, {
    variables: { offset: 0, limit: 10 },
    fetchPolicy: 'cache-and-network', // 避免重复的网络请求
  });
  const handleLoadMore = () => {
    fetchMore({
      variables: { offset: data.posts.length },
      updateQuery: (prev, { fetchMoreResult }) => {
        if (!fetchMoreResult) return prev;
        return Object.assign({}, prev, {
          posts: [...prev.posts, ...fetchMoreResult.posts],
        });
      },
    });
  };
  if (loading) return Loading...
;
  return (
    
      {data.posts.map((post) => (
        {post.title}
      ))}
      
    
  );
}
在这个示例中,当用户点击“Load More”按钮时,将触发一个新的网络请求并在缓存中更新数据,而不是发出两个重复的网络请求。