当新订阅到达 react-apollo 时如何重新获取查询 [英] How to refetch a query when a new subscription arrives in react-apollo

查看:114
本文介绍了当新订阅到达 react-apollo 时如何重新获取查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道当订阅接收到新数据时,是否有一种优雅的方式来触发 react-apollo 中查询的重新获取(这里的数据并不重要,将与之前的数据相同).我只是在这里使用订阅作为通知触发器,告诉 Query 重新获取.

I was wondering if there's an elegant way to trigger the refetch of a query in react-apollo when a subscription receives new data (The data is not important here and will be the same as previous one). I just use subscription here as a notification trigger that tells Query to refetch.

我尝试使用 Subscription 组件和 subscribeToMore 来调用 Query 子组件中的refetch"方法,但这两种方法都会导致无限重新获取.

I tried both using Subscription component and subscribeToMore to call "refetch" method in Query's child component but both methods cause infinite re-fetches.

注意:我使用的是 react-apollo v2.1.3 和 apollo-client v2.3.5

NOTE: I'm using react-apollo v2.1.3 and apollo-client v2.3.5

这是代码的简化版本

<Query
  query={GET_QUERY}
  variables={{ blah: 'test' }}
>
  {({ data, refetch }) => (
    <CustomComponent data={data} />
    //put subscription here? It'll cause infinite re-rendering/refetch loop
  )}
<Query>

推荐答案

最后,我从 Pedro 的回答中获得灵感,自己弄明白了.

Finally I figured it out myself with the inspiration from Pedro's answer.

想法:我面临的问题是我想在Subscription中调用Query的refetch方法,但是Query和Subscription组件都只能在render中访问方法.这是无限重新获取/重新渲染的根本原因.为了解决这个问题,我们需要将订阅逻辑从 render 方法中移出,并将其放在生命周期方法中的某个位置(即 componentDidMount),在触发 refetch 后不会再次调用它.然后我决定使用 graphql hoc 而不是 Query 组件,这样我就可以在组件的顶层注入像 refetchsubscribeToMore 这样的道具,这使得它们可以通过任何生命周期方法访问.

Thoughts: the problem I'm facing is that I want to call Query's refetch method in Subscription, however, both Query and Subscription components can only be accessed in render method. That is the root cause of infinite refetch/re-rendering. To solve the problem, we need to move the subscription logic out of render method and put it somewhere in a lifecycle method (i.e. componentDidMount) where it won't be called again after a refetch is triggered. Then I decided to use graphql hoc instead of Query component so that I can inject props like refetch, subscribeToMore at the top level of my component, which makes them accessible from any life cycle methods.

代码示例(简化版):

class CustomComponent extends React.Component {
  componentDidMount() {
    const { data: { refetch, subscribeToMore }} = this.props;

    this.unsubscribe = subscribeToMore({
      document: <SUBSCRIBE_GRAPHQL>,
      variables: { test: 'blah' },
      updateQuery: (prev) => {
        refetch();
        return prev;
      },     
    });
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  render() {
    const { data: queryResults, loading, error } } = this.props;

    if (loading || error) return null;

    return <WhatEverYouWant with={queryResults} />
  }
}

export default graphql(GET_QUERY)(CustomComponent);

这篇关于当新订阅到达 react-apollo 时如何重新获取查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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