【问题标题】:Use `useQuery` hook the same way as `useMutation` fails以与 `useMutation` 失败相同的方式使用 `useQuery` 钩子
【发布时间】:2021-09-17 16:46:47
【问题描述】:

使用 React 和 Apollo React 钩子

import { useCallback, useState } from "react";
import { useMutation, useSubscription, useQuery } from "@apollo/react-hooks";

我得到了一个函数useChannel,其中我的所有graphql 突变都有钩子。 每个突变都被导入,然后声明为常量,如下所示:

const [addExportChannel] = useMutation(AddExportChannelMutation);

我像这样在钩子的返回函数中使用它

  const onAddImportChannel = useCallback(
    async (props) => {
      try {
        const data = await addImportChannel({
          variables: {
            shopId,
            name: props.name,
            url: props.url,
            filetype: props.filetype
          }
        });
...

当我尝试对 useQuery 执行相同操作时,它会说 useQuery 不可迭代。 TypeError: useQuery is not a function or its return value is not iterable

 const [FeedProcess] = useQuery(GetFeedProcessQuery);
...
 const onFeedProcess = useCallback(
    async (props) => {
      try {
        const data = await FeedProcess({
          variables: { shopId, feedId: props.feedId }
        });
...

我在这里遗漏了什么,试图弄清楚这两个钩子有什么不同。

【问题讨论】:

    标签: reactjs react-hooks apollo react-apollo


    【解决方案1】:

    因为 useQuery 被立即调用,所以你不能像这样存储它 (const [FeedProcess] = useQuery(GetFeedProcessQuery);)。但是阿波罗有 useLazyQuery 可以像你一样存储。如果您想稍后存储和调用它,请改用 useLazyQuery。

    【讨论】:

      【解决方案2】:

      你应该像这样从 useQuery 钩子中解构 props:

      const {data, loading, error} = useQuery(GetFeedProcessQuery);
      

      【讨论】:

      • 这样查询被立即调用,但我想没有办法解决这个问题。 useMutation 示例中的 addExportChannel 只会在我在嵌套函数中调用它时运行。我不能自己嵌套 useQuery,因为这会违反钩子规则。我想使用 FeedProcess 作为 useQuery 的触发器。
      猜你喜欢
      • 1970-01-01
      • 2023-04-10
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 2020-08-22
      • 2020-04-27
      • 2020-10-19
      • 2020-11-08
      相关资源
      最近更新 更多