组件挂载上的 Apollo useQuery 挂钩
Apollo useQuery hook on component mount
我是 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
}
}
`;
这是一个关于如何使用 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`
来自 https://github.com/trojanowski/react-apollo-hooks/issues/158
我是 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
}
}
`;
这是一个关于如何使用 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`
来自 https://github.com/trojanowski/react-apollo-hooks/issues/158