【问题标题】:readFragment causing IntrospectionFragmentMatcher error although not using interface or unions尽管未使用接口或联合,但 readFragment 导致 IntrospectionFragmentMatcher 错误
【发布时间】:2019-08-13 07:51:13
【问题描述】:

尝试获取查询片段时出现以下错误:

“您正在使用简单(启发式)片段匹配器,但您的查询包含联合或接口类型。Apollo 客户端将无法准确映射片段。要消除此错误,请使用 IntrospectionFragmentMatcher 中所述文档:https://www.apollographql.com/docs/react/recipes/fragment-matching.html"

这是触发错误的调用。

const sourceData = cache.readFragment({
        id: `${typename}:${idToAdd}`,
        fragment: gql`
          ${sourceFragment}
        `,
      });

sourceFragment 在哪里

fragment series on PriceSeries {
    id
    title
    description
    commodity
    region
    location
    isDiscontinued
    order
}

Apollo 似乎将片段的返回值归类为联合或接口。我不认为添加 IntrospectionFragmentMatcher 应该是必要的,因为我们不需要联合或接口,尽管也许我错了。将__typename 添加到片段没有帮助。

  • 如何消除此错误(我可能只是缺少一些用于输入的 gql 语法?)
  • 使用片段是否意味着我们应该设置 IntrospectionFragmentMatcher 无论如何..(文档说它应该只需要 when using fragments on interfaces or unions 而我们不是)
  • 错误是错误吗,我是否应该隐藏错误(如果您忽略它,它确实可以正常工作)

更新

ApolloClient创建如下

 client = new ApolloClient({
      link: createLink('MY_URL', Apollo.fetch),
      cache: new InMemoryCache(),
    });

【问题讨论】:

  • 能否分享创建InMemoryCache实例的代码?
  • @User97 我已经添加了上面的代码,它目前没有自定义配置
  • 好的,只要${typename} 被正确传递,我看不出它有任何理由在这种情况下抛出错误。
  • 您是否使用writeQuerywriteFragment writeData 在代码中直接写入缓存?如果是这样,您是否在这样做时省略了写__typename
  • 调用“readFragment”时抛出错误,所以在任何写调用之前。我已经尝试将它们全部删除,但仍然收到相同的消息

标签: javascript reactjs apollo react-apollo apollo-client


【解决方案1】:

您需要创建 apollo 缓存并使用 dataIdFromObject 设置规范化功能。

import { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory';

const fragmentMatcher = new IntrospectionFragmentMatcher({
  // Here you may want to pass your introspection query result data,
});

const cache = new InMemoryCache({
  dataIdFromObject: o => o.id,
  fragmentMatcher,
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 2020-01-12
    • 2016-06-01
    • 2021-12-23
    相关资源
    最近更新 更多