【问题标题】:React-Apollo, don't run query on component loadReact-Apollo,不要在组件加载时运行查询
【发布时间】:2018-01-12 15:50:16
【问题描述】:

我正在使用很棒的 https://github.com/apollographql/react-apollo 库,我正在尝试看看是否有比我现在这样做更好的惯例来将数据加载到组件中。

我已经将我的组件设置为使用 apollo HOC 将数据加载到我的组件中,如下所示:

const mainQuery = gql`
  query currentProfileData($userId:String, $communityId:String!){
    created: communities(id:$communityId) {
      opportunities{
          submittedDate
          approvalDate
          status
          opportunity{
            id
          }
      }
    }
  }
`;
const mainQueryOptions = {
  options: {
    variables: { userId: '_', communityId: '_' },
  },
};

const ComponentWithData = compose(
  graphql(mainQuery, mainQueryOptions),
)(Component);

此设置效果很好,但存在一些问题。

  1. 我最终得到总是运行两次的查询,因为我需要将 props 传递给 apollo refetch 以进行查询。我还必须传入一些虚拟数据(也称为“_”)以防止获取无用的数据。

  2. 我最终不得不在 componentWillReceiveProps 中进行一些花哨的检查,以防止多次加载查询。

    • 我不能在查询中使用跳过选项,因为这会阻止重新获取函数被传入。

我没有完全避开 HOC 并直接通过 apollo 手动运行查询,我该如何解决这个问题?

【问题讨论】:

    标签: javascript reactjs graphql apollo


    【解决方案1】:

    只是一点点跟进。

    借助@daniel 的洞察力,我能够解决我的两个主要问题,使用道具运行查询,并有条件地跳过查询,直到它准备好。我只是想发布我的最终代码结果。由于您可以为这两个选项设置功能,这会很有帮助。

    const mainQueryOptions = {
      skip: ({ community: { id: communityId } }) => !communityId,
      options: ({ community: { id: communityId }, user: { id: userId = '_' } }) => ({
        variables: { userId, communityId },
      }),
    };
    

    您可以在 apollo api 页面上找到更多信息:http://dev.apollodata.com/react/api-graphql.html#graphql

    【讨论】:

    • 感谢分享!
    【解决方案2】:

    如果您使用组件的 props 作为 refetch 调用中使用的变量,实际上有一种更简洁的方法。 options 属性实际上可以是一个获取组件道具的函数。这使您可以从传递给组件的道具中派生变量。它看起来像这样:

    const mainQueryOptions = {
      options: ({ userId, communityId }) => ({
        variables: { userId, communityId },
      },
    });
    

    【讨论】:

    • 这样哇。我从来不知道你能做到这一点。不知道我怎么错过了!我深入一点,发现你可以有条件地跳过,解决我的另一个主要问题。非常感谢!
    猜你喜欢
    • 2017-11-15
    • 2017-11-16
    • 2017-04-22
    • 2019-03-14
    • 2016-11-30
    • 2020-10-01
    • 2018-11-06
    • 2018-07-09
    • 2017-03-25
    相关资源
    最近更新 更多