【发布时间】: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