执行Apollo Client查询时,我遇到了触发onCompleted回调的问题。
查询运行没有问题,它返回我期望的结果,但onCompleted处理程序永远不会触发。我尝试过多种方法:
有一个与我正在经历的相关的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);
*/
在这一点上,我完全被难倒了。任何帮助,将不胜感激。
图书馆版本
(回答这个问题,因为它收到了大量的意见)。
截至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);