onCompleted处理程序不使用Apollo客户端查询触发

问题描述 投票:0回答:1

执行Apollo Client查询时,我遇到了触发onCompleted回调的问题。

查询运行没有问题,它返回我期望的结果,但onCompleted处理程序永远不会触发。我尝试过多种方法:

  • a)我尝试过使用HOC而不是React组件(请参阅gist结尾处的注释)
  • b)我尝试使缓存无效并将fetchPolicy设置为'仅网络'
  • 我已经尝试将处理程序设置为“异步”

有一个与我正在经历的相关的Github开放问题,但是此线程中的人只在从缓存加载时遇到问题。我正在经历回调而不是一直开火。 https://github.com/apollographql/react-apollo/issues/2177

这是我的代码的修剪示例:

import React from 'react';
import { graphql, Query } from 'react-apollo';
import { ProductQuery } from '../../graphql/Products.graphql';

class EditProductVisualsPage extends React.Component {
  constructor() {
    super();
  }

  render() {
    const { productId } = this.props;
    return (
      <Query
        query={ProductQuery} 
        variables={{ id: productId }}
        onCompleted={data => console.log("Hi World")}>
        {({ loading, data: { product } }) => (
          /* ... */ 
        )}
      </Query>
    );
  }
}

export default EditProductVisualsPage;

/*
export default graphql(ProductQuery, {
  options: props => ({
    variables: {
      id: props.productId,
    },
    fetchPolicy: "cache-and-network",
    onCompleted: function() {
      debugger;
    },
  }),
})(EditProductVisualsPage);
*/

在这一点上,我完全被难倒了。任何帮助,将不胜感激。

图书馆版本

  • react-apollo(2.1.4)
  • apollo-client(2.3.1)
  • 反应(32年3月16日)
reactjs apollo react-apollo apollo-client
1个回答
0
投票

(回答这个问题,因为它收到了大量的意见)。

截至2019年4月,onCompleted处理程序仍然存在问题。但是,它可以通过使用withApollo HOC来解决。 https://www.apollographql.com/docs/react/api/react-apollo#withApollo

这是一个示例集成:

import React from 'react';
import { withApollo } from 'react-apollo';

class Page extends React.Component {
  constructor(props) {
    super();
    this.state = {
      loading: true,
      data: {},
    };
    this.fetchData(props);
  }

  async fetchData(props) {
    const { client } = props;
    const result = await client.query({
      query: YOUR_QUERY_HERE, /* other options, e.g. variables: {} */     
    });

    this.setState({
      data: result.data,
      loading: false,
    });
  }

  render() {
    const { data, loading } = this.state;
    /* 
      ... manipulate data and loading from state in here ...
    */
  }
}
export default withApollo(Page);
© www.soinside.com 2019 - 2024. All rights reserved.