React-Apollo,不要在组件加载时运行查询 [英] React-Apollo, don't run query on component load

查看:23
本文介绍了React-Apollo,不要在组件加载时运行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using the awesome https://github.com/apollographql/react-apollo library and I'm trying to see if there is a better convention to load data into components than how I'm doing it now.

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

I've set up my components to with the apollo HOC to load data into my components, like so:

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);

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

This setup works great, but with some problems.

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

  1. I end up with queries that always run twice, as I need to pass props to apollo refetch for the query. I also have to pass in some dummy data (aka the "_") to prevent useless data fetching.

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

I end up having to do some fancy checking in componentWillReceiveProps to prevent loading the query multiple times.

  • 我无法在查询中使用跳过选项,因为这会阻止传入重新获取函数.

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

Short of my sidestepping the HOC all together and manually running the queries through apollo directly, how can I solve this?

推荐答案

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

If you're utilizing your component's props as the variables used in the refetch call, there is in fact a cleaner approach. The options property can actually be a function that takes your component's props. This lets you derive your variables from the props passed to your component. It would look something like this:

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

这篇关于React-Apollo,不要在组件加载时运行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆