gpt4 book ai didi

javascript - 使用查询钩子(Hook) react Apollo 条件调用

转载 作者:行者123 更新时间:2023-12-03 13:28:21 24 4
gpt4 key购买 nike

我一直在使用 react-apollo 和 render prop 方法。

这工作得很好,我的代码看起来像这样。

const App = () => {
const [player, setPlayer] = React.useState(null);
if (player) {
return (
<GetBroncosPlayerQuery variables={{ player }}>
{({ data }) => {
// do stuff here with a select box
}}
</GetBroncosPlayersQuery>
)
}
}

现在,如果我尝试使用 useQuery 钩子(Hook)执行相同的操作,当我的代码如下所示时,我会收到以下错误:

const App = () => {
const [player, setPlayer] = React.useState(false);

if (isBroncos) {
const { data } = useQuery(GetBroncosPlayersQueryDocument, {
variables: { player }
});
// do stuff here
}
}

这会产生错误,表明您无法在条件语句中使用 Hook 。然后我实现了 useLazyQuery 但这也不起作用 call it once it behaves like useQuery ,所以它第一次可以工作,但是如果用户将选择下拉列表再次更改为空,它就会中断。

仅有条件地调用查询的查询 Hook 的最佳方法是什么?

最佳答案

您应该使用skip option :

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 && <>...</>;
};

关于javascript - 使用查询钩子(Hook) react Apollo 条件调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59489097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com