使用查询挂钩反应Apollo条件调用

时间:2019-12-26 13:21:29

标签: javascript reactjs ecmascript-6 react-apollo

我一直在使用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钩子执行相同的操作,则我的代码如下所示时,出现以下错误:

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之后还是不起作用,因此它第一次起作用,但是如果用户将选择下拉列表再次更改为空,则会中断。

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

1 个答案:

答案 0 :(得分:1)

您应该使用skip option

  

如果skip为true,则将完全跳过查询。

const isBroncos = getCondition();

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

  const { data } = useQuery(GetBroncosPlayersQueryDocument, {
    variables: { player },
    skip: isBroncos
  });

  return !isBroncos && data && <>...</>;
};