使用查询挂钩反应Apollo条件调用 [英] use query hook react Apollo conditional call
问题描述
我一直在使用react-apollo
和render prop方法.
I have been using react-apollo
and the render prop approach.
这很好用,我的代码看起来像这样.
This worked perfectly and my code looked something like this.
const App = () => {
const [player, setPlayer] = React.useState(null);
if (player) {
return (
<GetBroncosPlayerQuery variables={{ player }}>
{({ data }) => {
// do stuff here with a select box
}}
</GetBroncosPlayersQuery>
)
}
}
现在,如果我尝试使用useQuery
钩子执行相同的操作,则我的代码如下所示时,出现以下错误:
Now, if I try doing the same with the useQuery
hook I get the following error, when my code looks like this:
const App = () => {
const [player, setPlayer] = React.useState(false);
if (isBroncos) {
const { data } = useQuery(GetBroncosPlayersQueryDocument, {
variables: { player }
});
// do stuff here
}
}
这会导致错误,您不能在条件语句中使用钩子.然后,我实现了useLazyQuery
,但这与您调用它的行为就像useQuery
一样,因此它可以首次使用,但是如果用户将选择下拉列表再次更改为空,则会中断.
This gives an error that you cannot use a hook in a conditional statement. I then implemented useLazyQuery
but this doesn't work either as after you call it once it behaves like useQuery
, so it works the first time, but if the user changes a select dropdown to be empty again it breaks.
使用查询挂钩仅有条件地调用查询的最佳方法是什么?
What is the best approach with the query hook to only call the query conditionally?
推荐答案
您应使用 skip
选项:
You should use skip
option:
如果skip为true,则将完全跳过查询.
If skip is true, the query will be skipped entirely.
const isBroncos = getCondition();
const App = () => {
const [player, setPlayer] = React.useState(false);
const { data } = useQuery(GetBroncosPlayersQueryDocument, {
variables: { player },
skip: isBroncos
});
return !isBroncos && data && <>...</>;
};
这篇关于使用查询挂钩反应Apollo条件调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!