无法读取 GraphQL Apollo Client 中的属性查询

Cannot read proper query in GraphQL Apollo Client

在我的应用程序的一个页面上,我正在使用 graphql apollo 客户端进行两次 api 调用。一个是 document,另一个是 menu。我的一个组件中需要菜单数据,所以我想使用 readQuery 以免再次获取它。我正在做的是:

const client = useApolloClient();

  try {
const testData = client.readQuery({
  query: gql`
  query ($result: String) {
    menu(result:  $result) {
      text
    }
  }
`,
  variables: {
    result: „testresult”
  },
});
console.log(testData);
} catch(e) {
  console.log(e);
}

graphQL 正在做的是寻找 document 根查询,所以错误看起来像这样:

Invariant Violation: Can't find field menu({"lang":"en-us"}) on object 

{
  "document({\"lanf\":\"en-us\",\"id\":\"mySite\"})": {
    "type": "id",
    "generated": false,
    "id": "XO5tyxAAALGzcYGG",
    "typename": "Document"
  }
}.

我认为是因为菜单数据还没有。

我怎样才能等到它出现?

你是对的。您收到错误消息,因为数据尚未在缓存中:

The query method, on the other hand, may send a request to your server if the appropriate data is not in your cache whereas readQuery will throw an error if the data is not in your cache. readQuery will always read from the cache.

https://www.apollographql.com/docs/react/advanced/caching/#readquery

要执行您想要的操作,请使用带有 cache-only fetchPolicy 的普通查询。 https://www.apollographql.com/docs/react/api/react-apollo/#optionsfetchpolicy