使用查询钩子反应阿波罗条件调用

use query hook react Apollo conditional call

我一直在使用 react-apollo 和渲染道具方法。

效果很好,我的代码看起来像这样。

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

现在,如果我尝试用 useQuery 钩子做同样的事情,我会收到以下错误,当我的代码如下所示时:

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

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

这给出了一个错误,你不能在条件语句中使用钩子。然后我实现了 useLazyQuery 但这在你 call it once it behaves like useQuery 之后也不起作用,所以它第一次起作用,但如果用户再次将 select 下拉列表更改为空,它就会中断。

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

你应该使用 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 && <>...</>;
};