可以使用Apollo的“cache-first”策略来避免这个问题。这种策略将首先尝试从缓存中获取数据,如果获取失败,才会发起网络请求获取数据。
示例代码:
import { ApolloLink } from 'apollo-link';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import ApolloClient from 'apollo-client';
const httpLink = new HttpLink({ uri: 'http://example.com/graphql' });
const cache = new InMemoryCache();
const client = new ApolloClient({
link: ApolloLink.from([
new ApolloLink((operation, forward) => {
const { operationName } = operation;
if (operationName === 'SomeQuery') {
operation.extensions.cachePolicy = {
type: 'cache-first',
};
}
return forward(operation);
}),
httpLink,
]),
cache,
});
在上面的示例中,我们使用ApolloLink
实例化了一个新的客户端。同时,在cachePolicy
扩展字段中,我们设置了“cache-first”策略,来优先从缓存中获取数据。在默认情况下,如果未提供cachePolicy
,则策略为“cache-and-network”。