Mel*_*Mel 2 apollo graphql react-apollo react-hooks
我是 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 (<>
...
</>)
}
Run Code Online (Sandbox Code Playgroud)
但这给了我一个错误
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:
Run Code Online (Sandbox Code Playgroud)
编辑:这是查询
import { gql } from '@apollo/client';
export const ME = gql`
query me {
profile {
firstName
lastName
}
}
`;
Run Code Online (Sandbox Code Playgroud)
这是一个关于如何使用 useQuery 挂钩然后将数据存储在状态中的示例
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`
Run Code Online (Sandbox Code Playgroud)
来自https://github.com/trojanowski/react-apollo-hooks/issues/158
| 归档时间: |
|
| 查看次数: |
1600 次 |
| 最近记录: |