需要在 Query 组件中进行处理,通过设置 fetchPolicy 和 returnPartialData 参数,来获取缓存中的数据,同时使得不会在缓存中找到数据时返回错误。代码示例如下:
import { useQuery } from '@apollo/react-hooks';
import { gql } from 'apollo-boost';
const GET_POSTS = gql`
query GetPosts {
posts {
id
title
}
}
`;
function PostList() {
const { loading, data } = useQuery(GET_POSTS, {
fetchPolicy: 'cache-and-network',
returnPartialData: true,
});
if (loading && !data) {
return Loading...;
}
const posts = data.posts || [];
return (
{posts.map(post => (
- {post.title}
))}
);
}
在上面的例子中,我们设置了 fetchPolicy 参数为 'cache-and-network',这意味着 useQuery 钩子将首先尝试从缓存中获取数据,如果找到了,则返回缓存中的数据,并尝试发起网络请求来获取最新的数据。如果网络请求成功,则返回最新的数据并将其存储在缓存中。如果在缓存中找不到数据,则返回返回PartialData 参数中定义的数据(在本例中为 posts)。最后,我们将返回的数据存储在变量中,并在组件中使用它来渲染一个帖子列表。