使用apollo-link-state查询报错:Field <name>不存在于Query类型
解决Apollo Link State查询时"Field doesn't exist on type 'Query'"的问题
嘿,作为刚接触Apollo和GraphQL的新手,遇到这个问题太正常啦!我来帮你捋清楚问题出在哪,以及怎么解决:
问题根源
你已经在defaults里设置了currentGame的初始值,但Apollo并不知道这个字段应该属于Query类型——默认的GraphQL schema里没有这个自定义的本地状态字段,所以查询时会抛出字段不存在的错误。
解决方案步骤
添加Resolvers,声明Query字段
你需要在withClientState配置里加上resolvers,告诉Apollo如何从缓存中读取currentGame字段:const stateLink = withClientState({ cache: stateCache, defaults: { currentGame: { __typename: 'currentGame', teamAScore: 0 } }, // 新增这部分resolvers resolvers: { Query: { currentGame: (_, __, { cache }) => { // 从缓存中读取currentGame数据 const { currentGame } = cache.readQuery({ query: gql` query GetCurrentGame { currentGame { __typename teamAScore } } ` }); return currentGame; } } } });完善你的查询语句
确保你的查询明确包含currentGame的字段,并且带上__typename(这对Apollo的缓存机制至关重要):const getCurrentGame = gql` query GetCurrentGame { currentGame { __typename teamAScore } } `;确认Cache实例正确
别忘了你的stateCache得是一个有效的InMemoryCache实例:import { InMemoryCache } from '@apollo/client'; const stateCache = new InMemoryCache();
额外提示
apollo-link-state的核心就是通过resolvers把本地状态的字段“挂载”到GraphQL的Query/Mutation类型上,这样Apollo才能识别这些自定义字段。只要把resolvers配置好,这个错误就会消失啦!
内容的提问来源于stack exchange,提问作者tnunamak
相关产品推荐
相关产品推荐

