mic*_*man 2 react-apollo react-hooks react-apollo-hooks
如何使用带有 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 } })
Run Code Online (Sandbox Code Playgroud)
但是,当我运行我的项目时,react-hooks 会给我以下消息:
“index.js:1437 警告:React 检测到 Upgrade 调用的 Hooks 的顺序发生了变化。如果不修复,这将导致错误和错误。有关更多信息,请阅读 Hooks 规则”
我想知道如何使用 react-apollo-hooks 来运行依赖于另一个查询的查询。如果预先知道 graphql 查询变量,则效果很好。但是,我没有找到来自其他查询的变量的解决方案。
这里的问题是,在所有钩子都有机会运行之前,您就短路了。
如果在所有钩子有机会被调用之前退出渲染函数,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} />
}
Run Code Online (Sandbox Code Playgroud)
修理:
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} />
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4406 次 |
| 最近记录: |