React-Apollo,不要对组件加载运行查询

Jus*_*tin 7 javascript apollo reactjs graphql

我正在使用awesome 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);
Run Code Online (Sandbox Code Playgroud)

这个设置很好,但有一些问题.

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

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

    • 我不能在查询中使用skip选项,因为这会阻止重新获取函数的传入.

我没有将HOC全部放在一起并直接通过apollo手动运行查询,我该如何解决?

Jus*_*tin 12

只需一点跟进.

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

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

你可以找到阿波罗API页面放在这里更多的信息:http://dev.apollodata.com/react/api-graphql.html#graphql


Dan*_*den 6

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

const mainQueryOptions = {
  options: ({ userId, communityId }) => ({
    variables: { userId, communityId },
  },
});
Run Code Online (Sandbox Code Playgroud)