【问题标题】:Is it possible to `readFragment` from apollo cache if it has no id?如果没有 id,是否可以从 apollo 缓存中“读取片段”?
【发布时间】:2021-09-30 12:06:10
【问题描述】:

我的应用中有一个嵌套组件。

在页面顶部,我有一个类似的查询

const REPOSITORY_PAGE_QUERY = gql`
  query RepositoryPageQuery($name: String!, $owner: String!) {
    repository(name: $name, owner: $owner) {
      ...RepositoryDetailsFragment
    }
  }
  ${REPOSITORY_DETAILS_FRAGMENT}
`;

RepositoryDetailsFragment 然后包括

// list of branches
refs(first: 2, refPrefix: "refs/heads/") {
  ...BranchesFragment
}

最后

fragment BranchesFragment on RefConnection {
    totalCount
    pageInfo {
      ...PageInfoFragment
    }
    edges {
      node {
        id
        name
      }
    }
  }
  ${PAGE_INFO_FRAGMENT}

显然,我不高兴,因为我需要传递BranchesFragment 信息大约 3 级。

相反,如果我可以直接在我的BranchesList 组件中从缓存中读取它,那就太好了。 我尝试使用

client.cache.readFragment({
   fragment: BRANCHES_FRAGMENT,
   fragmentName: "BranchesFragment"
});

但问题是这个片段没有任何 id。有什么办法可以处理并获取片段信息?

【问题讨论】:

    标签: apollo-client react-apollo


    【解决方案1】:

    好吧,我突然想到了解决方案。也许它对其他人有用。

    假设我们有一个查询层次结构 -> 片段和组件 -> 子组件,如下所示:

    RootPageComponent 查询

    query RepositoryPageQuery(
        $name: String!
        $owner: String!
        $count: Int!
        $branchSearchStr: String!
      ) {
        repository(name: $name, owner: $owner) {
          ...RepositoryDetailsFragment
        }
      }
      ${REPOSITORY_DETAILS_FRAGMENT}
    

    组件返回以下内容

    <RepositoryDetails repository={data.repository} />
    

    存储库详细信息 有一个片段

    fragment RepositoryDetailsFragment on Repository {
        name
        descriptionHTML
        defaultBranchRef {
          id
          name
        }
        # the branches repository has
        refs(first: $count, refPrefix: "refs/heads/", query: $branchSearchStr) {
          ...BranchesFragment
        }
      }
      ${BRANCHES_FRAGMENT}
    

    并返回&lt;BranchesList /&gt; 组件。

    所以,不要将 branch.info 从 RootPage 传递到 RepositoryDetails,然后再传递到 BranchesList

    您可以在BranchesList中执行以下操作

    const client = useApolloClient();
    
    client.cache.readFragment({
        fragment: BRANCHES_FRAGMENT,
        fragmentName: "BranchesFragment",
        id: "RefConnection:{}" // note this {} - apollow cache adds it when no id is present for the object
    })
    

    重要!

    确保同时更新该字段的type policy 并设置keyArgs to []

    所以在这种特殊情况下:

    RefConnection: {
      keyFields: []
      ...
    }
    

    这将给出相同的结果,但您不必将 props 传递给嵌套组件,而是可以直接从缓存中读取(就像使用 redux 一样)

    【讨论】:

      猜你喜欢
      • 2021-05-27
      • 1970-01-01
      • 2020-07-23
      • 2010-09-21
      • 2020-10-25
      • 2021-06-05
      • 2022-01-08
      • 2012-01-13
      • 1970-01-01
      相关资源
      最近更新 更多