2

如何将 2 个 graphql 查询与 react-apollo-hooks 一起使用,其中第二个查询取决于从第一个查询中检索到的参数?

我尝试使用 2 个查询,如下所示:

const [o, setO] = useState()

const { loading: loadingO, error: errorO, data: dataO } = useQuery(Q_GET_O, { onCompleted: d => setO(d.getO[0].id) });

if (loadingO) { return "error" }

const { loading: loadingOP, error: errorOP, data: dataOP } = useQuery(Q_GET_OP, { variables: { o } })

但是,当我运行我的项目时,react-hooks 会给我以下消息:

“index.js:1437 警告:React 检测到 Upgrade 调用 Hooks 的顺序发生了变化。如果不修复,这将导致错误和错误。有关更多信息,请阅读 Hooks 规则”

我想知道如何使用 react-apollo-hooks 来运行依赖于另一个查询的查询。如果事先知道 graphql 查询变量,它会很好用。但是,我没有找到来自其他查询的变量的解决方案。

4

2 回答 2

5

这里的问题是,在所有钩子有机会运行之前,您就短路了。

如果你在所有钩子有机会被调用之前退出渲染函数,React 会报错。

例如:

function BrokenFoo () {
  const query = useSomeQuery();
  if (query.loading) return <Loading />

  // This will cause some issues because 
  // it's possible that we return before our useState hook gets called

  const [bar, setBar] = useState();

  return <SomeComponent bar={bar} setBar={setBar} data={query.data} />
}

修理:

function FixedFoo () {
  // This will be fine because 
  // all of the hooks have a chance to be called before a return
  const query = useSomeQuery();
  const [bar, setBar] = useState();

  if (query.loading) return <Loading />

  return <SomeComponent bar={bar} setBar={setBar} data={query.data} />
}
于 2019-10-11T14:34:27.563 回答
3

您可以将skip选项添加到第二个查询并丢失 if 条件:

const { loading: loadingOP, error: errorOP, data: dataOP } 
    = useQuery(Q_GET_OP, { variables: { o }, skip: !o  })

来自文档: If skip is true, the query will be skipped entirely

于 2019-08-19T18:05:47.167 回答