【问题标题】:Apollo useQuery hook on component mount组件挂载上的 Apollo useQuery hook
【发布时间】:2021-03-15 20:37:02
【问题描述】:

我是 hooks 的新手,并试图更多地使用它们

组件挂载时如何获取数据(使用 Apollo)?

我正在尝试在 useEffect 中使用 useQuery,目前我的代码如下所示

const MyComponent = () => {
  const getME = () => {
      const { loading, error, data } = useQuery(ME);
      setMe(data.me) // useState hook
      console.log('query me: ', me);
  };

  useEffect(getME);
  return (<>
  ...
  </>)
}

但这给了我一个错误

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

编辑:这是查询

import { gql } from '@apollo/client';

export const ME = gql`
  query me {
    profile {
      firstName
      lastName
    }
  }
`;

【问题讨论】:

  • 您好 Mel,您能否为您尝试调用的钩子添加更多上下文
  • 我刚刚添加了一些上下文
  • 不需要 ... useQuery 在启动时已经触发 ... data 准备好在加载后呈现

标签: graphql react-hooks apollo react-apollo


【解决方案1】:

这是一个示例,说明您应该如何使用 useQuery 挂钩,然后将数据存储在 state 中

const { loading, data, error } = useQuery(SOME_QUERY)
const [state, setState] = React.useState([])

useEffect(() => {
  // do some checking here to ensure data exist
  if (data) {
    // mutate data if you need to
    setState(data)
  }
}, [data])`enter code here`

来自https://github.com/trojanowski/react-apollo-hooks/issues/158

【讨论】:

  • 不用把data复制成state,也是一样的……可以直接使用data……当然是加载后
猜你喜欢
  • 2019-12-22
  • 2021-05-27
  • 2020-04-13
  • 2020-05-11
  • 2020-12-14
  • 1970-01-01
  • 2021-01-20
  • 2022-06-21
  • 2021-10-27
相关资源
最近更新 更多