React-Apollo,不要对组件加载运行查询 [英] React-Apollo, don't run query on component load
问题描述
我正在使用精彩的 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.
-
我最终会遇到总是运行两次的查询,因为我需要将道具传递给apollo refetch进行查询。我还必须传入一些虚拟数据(又名_)以防止无用的数据提取。
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.
- 我无法在查询中使用skip选项,因为这会阻止重新获取功能被传入。
我没有回避HOC并手动运行通过apollo直接查询,我该如何解决?
Short of my sidestepping the HOC all together and manually running the queries through apollo directly, how can I solve this?
推荐答案
如果你正在利用组件的道具作为变量中使用的变量 refetch
调用,实际上是一种更清洁的方法。 选项
属性实际上可以是一个获取组件道具的函数。这使您可以从传递给组件的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屋!