我正在使用graphql和react-apollo构建一个React应用程序。
以前,我曾使用过这些库,并且根据我的经验,在使用graphql
HOC向组件添加查询时,该查询应在第一个渲染器上自动触发。但是由于某种原因,这似乎不再起作用。
我有这个简单的组件:
import React from 'react';
import { graphql } from 'react-apollo';
import { getUser } from '../common/graphql/queries/user.query';
class Home extends React.Component {
render() {
const { classes = {} } = this.props;
console.log(this.props);
return (
<div className={classes.home}>
Hello World!
</div>
);
}
}
export default graphql(getUser, { name: 'getUser' })(Home);
我期望getUser
查询会自动触发,但根本不会触发。如果我在Chrome中检查“网络”选项卡,即使没有getUser
对象在我的道具中,也没有对graphql端点的调用。
但是,如果我尝试强制进行重新提取,则查询将按预期工作:
class Home extends React.Component {
constructor(props) {
super(props);
this.fetch = true;
}
render() {
const { classes = {} } = this.props;
console.log(this.props);
if(this.fetch) {
this.props.getUser.refetch();
this.fetch = false;
}
return (
<div className={classes.home}>
Hello World!
</div>
);
}
}
这是我的阿波罗配置:
import url from "url";
import { ApolloClient } from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import { withClientState } from "apollo-link-state";
import { HttpLink } from "apollo-link-http";
import { ApolloLink } from "apollo-link";
import resolvers from "./common/graphql/resolvers";
import * as defaults from "./common/graphql/defaults";
const BASE_URL = process.env.BASE_URL || "http://localhost:8081";
console.log(BASE_URL);
const apollo = () => {
// Server side rendering work around
const httpLinkOptions = { uri: url.resolve(BASE_URL, "graphql") };
const httpLink = new HttpLink(httpLinkOptions);
const cache = new InMemoryCache({
dataIdFromObject: ({ id }) => id
});
const stateLink = withClientState({
cache,
resolvers,
defaults: { ...defaults, user: null, auth: null, categories: [] },
});
const link = ApolloLink.from([
stateLink,
httpLink
]);
const client = new ApolloClient({
link,
cache,
addTypename: false,
dataIdFromObject: ({ id }) => id
});
return client;
};
export default apollo;
我已经进行了一些研究,似乎最近没有发生任何会改变这种行为的重大更新。有谁知道为什么会这样?