React-Apollo,不要对组件加载

时间:2017-08-04 16:12:12

标签: javascript reactjs graphql apollo

我正在使用令人敬畏的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. 我最终会遇到总是运行两次的查询,因为我需要为查询传递道具到apollo refetch。我还必须传入一些虚拟数据(又名“_”)以防止无用的数据提取。

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

    • 我无法在查询中使用skip选项,因为这会阻止传入重新获取功能。
  3. 由于我没有直接回避HOC并直接通过apollo手动运行查询,我该如何解决?

2 个答案:

答案 0 :(得分:12)

稍微跟进一下。

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

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

答案 1 :(得分:4)

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

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