渲染了比上一次渲染更多的钩子

Rendered more hooks than during the previous render

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

我尝试使用 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 Warning: React has detected a change in the order of Hooks called by Upgrade. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks"

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

您可以将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

这里的问题是你在所有的钩子有机会 运行 之前短路返回。

如果您在所有钩子都有机会被调用之前退出渲染函数,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} />
}