【问题标题】:use query hook react Apollo conditional call使用查询钩反应 Apollo 条件调用
【发布时间】:2020-04-16 17:40:03
【问题描述】:

我一直在使用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,所以它第一次起作用,但如果用户将选择下拉列表再次更改为空,它会中断。

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

【问题讨论】:

    标签: javascript reactjs ecmascript-6 react-apollo


    【解决方案1】:

    你应该使用skip option:

    如果skip为真,查询将被完全跳过。

    const isBroncos = getCondition();
    
    const App = () => {
      const [player, setPlayer] = React.useState(false);
    
      const { data } = useQuery(GetBroncosPlayersQueryDocument, {
        variables: { player },
        skip: isBroncos
      });
    
      return !isBroncos && data && <>...</>;
    };
    

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 2020-10-19
      • 2021-07-16
      • 2020-08-20
      • 2021-03-02
      • 2019-12-20
      • 2021-01-27
      • 2017-02-08
      • 2020-11-11
      相关资源
      最近更新 更多