【问题标题】:React - Using a custom hook to call another hook - a clean approach?React - 使用自定义钩子调用另一个钩子 - 一种干净的方法?
【发布时间】:2021-01-31 17:30:46
【问题描述】:

我正在使用 next.js 在 React 中编写一个应用程序。

我有一个需要执行的 GraphQL 查询 - 我只想执行它并获得结果,但是遇到了问题。

所以如果我像下面这样调用useQuery 钩子,它会返回响应:

import { useQuery } from 'react-apollo';

export function LaunchesFunctionTwo() {
  const { loading, error, data } = useQuery(GET_SUBSCRIPTION_BY_ID)

  // I see the data I want returned here ok
  console.log(data)

  // I don't need to display anything I just want the data - hence this empty string
  // Infact, thats probably a second question, how can I just use useQuery on its own
  return ''
 
}

但是,如果在 Index 组件中,我也会这样做,console.log(data) 返回 undefined ,就像这样:

import { useQuery } from 'react-apollo';

export default function Index(props) {
  const { loading, error, data } = useQuery(GET_SUBSCRIPTION_BY_ID)

  // Doing this however returns me undefined
  console.log(data)

   return (<div>...</div>)
}

更新: 我得到了这个工作。我读到我们可以使用 Hooks 的仅有的两个地方之一是:Call Hooks from custom Hooks

所以我做了一个这样的自定义钩子:

根据文档,use 关键字是必需的:

export function useLaunchesFunctionTwo() {
  const { loading, error, data } = useQuery(GET_SUBSCRIPTION_BY_ID)

  return data
}

然后在我的 index.js 中,我可以简单地调用 useLaunchesFunctionTwo 来获取我的数据。

所以现在的问题 - 这是一种有效的工作方式。我能把我的代码组织得更清楚一点吗?

任何帮助表示赞赏。

【问题讨论】:

  • useQuery 不是异步的吗?

标签: reactjs next.js react-apollo


【解决方案1】:

看起来您没有在索引中导入 useQuery

import { useQuery } from 'react-apollo';

【讨论】:

    猜你喜欢
    • 2020-10-16
    • 2022-10-09
    • 2021-06-02
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多