Apollo Client缓存读取策略,是用于决定在Apollo Client缓存中查找数据的策略。其默认值为“cache-first”,它会先在缓存中查找数据,如果找到则直接返回该数据,否则再去请求服务器获取数据。
除了“cache-first”之外,还有其他几种缓存读取策略可以选择:
以“cache-and-network”为例,以下是使用Apollo Client时如何设置缓存读取策略的代码示例:
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';
const cache = new InMemoryCache();
const link = new HttpLink({
uri: 'https://mygraphqlapi.com/graphql'
});
const client = new ApolloClient({
cache,
link,
defaultOptions: {
query: {
// 设置缓存读取策略为“cache-and-network”
fetchPolicy: 'cache-and-network'
}
}
});