GraphQL Apollo 客户端与缓存策略最佳实践概述Apollo Client 通过规范化缓存与 `typePolicies` 提供细粒度的更新与合并控制。本文以稳定 API 展示查询、变更与缓存策略。客户端初始化与查询import { ApolloClient, InMemoryCache, HttpLink, gql } from '@apollo/client'
const client = new ApolloClient({
link: new HttpLink({ uri: '/graphql' }),
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
products: {
keyArgs: ['filter'],
merge(existing = [], incoming: any[]) {
return [...existing, ...incoming]
},
},
},
},
},
}),
})
const PRODUCTS = gql`query Products($filter: String){ products(filter:$filter){ id title } }`
变更与局部更新import { useMutation, gql } from '@apollo/client'
const ADD_PRODUCT = gql`mutation($title:String!){ addProduct(title:$title){ id title } }`
function AddButton() {
const [mutate] = useMutation(ADD_PRODUCT, {
update(cache, { data }) {
cache.modify({
fields: {
products(existing = []) {
return [data?.addProduct, ...existing]
},
},
})
},
})
return <button onClick={() => mutate({ variables: { title: 'New' } })}>Add</button>
}
SSR 集成要点在服务端执行初始查询并注入缓存快照;客户端复用同一缓存配置进行水合。明确 `keyArgs` 与 `merge` 策略,避免重复项与分页错乱。验证要点API 为稳定版本;通过开发者工具与网络面板验证查询/变更与缓存命中。在分页、筛选与乐观更新场景中检查规范化缓存的正确性。

发表评论 取消回复