我正在使用很棒的 https://github.com/apollographql/react-apollo库,我正在尝试查看是否有比我现在做的更好的约定来将数据加载到组件中。
我已经将我的组件设置为使用 apollo HOC 将数据加载到我的组件中,如下所示:
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);
此设置运行良好,但存在一些问题。
我最终遇到了总是运行两次的查询,因为我需要将 props 传递给 apollo refetch 以进行查询。我还必须传递一些虚拟数据(又名“_”)以防止无用的数据获取。
我最终不得不在 componentWillReceiveProps 中做一些花哨的检查以防止多次加载查询。
- 我不能在查询中使用跳过选项,因为这会阻止传入重新获取函数。
如果我不一起回避 HOC 并直接通过 apollo 手动运行查询,我该如何解决这个问题?
最佳答案
只是一点点跟进。
凭借@daniel 的洞察力,我能够解决我的 2 个主要问题,使用 props 运行查询,并有条件地跳过查询直到它准备好。我只想发布我的最终代码结果。由于您可以为这两个选项设置功能,因此很有帮助。
const mainQueryOptions = {
skip: ({ community: { id: communityId } }) => !communityId,
options: ({ community: { id: communityId }, user: { id: userId = '_' } }) => ({
variables: { userId, communityId },
}),
};
您可以在 apollo api 页面上找到更多信息:http://dev.apollodata.com/react/api-graphql.html#graphql
关于javascript - React-Apollo,不要在组件加载时运行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45511335/