解决这个问题的方法是使用React的状态管理工具,例如useState或useReducer来记录值。以下是一个示例代码:
import React, { useState, useEffect } from "react";
import { useQuery, ApolloProvider, ApolloClient, InMemoryCache, gql } from "@apollo/client";
import { createHttpLink } from "apollo-link-http";
const httpLink = createHttpLink({
uri: "your-graphql-endpoint"
});
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
});
const GET_DATA = gql`
query GetData {
// your query here
}
`;
const MyComponent = () => {
const [data, setData] = useState(null);
const { loading, error } = useQuery(GET_DATA, {
onCompleted: (data) => setData(data)
});
useEffect(() => {
if (data) {
// do something with the data
console.log(data);
}
}, [data]);
if (loading) return Loading...
;
if (error) return Error :(
;
return (
{/* render your component */}
);
};
const App = () => (
);
export default App;
在上面的代码中,我们使用useState钩子来创建一个名为data的状态变量,并使用setData函数来更新它。在useQuery的onCompleted回调函数中,我们将从Apollo获取的数据设置为data状态变量。然后,我们使用useEffect来监听data变量的变化,并在变化时执行一些操作。最后,我们在MyComponent组件中使用ApolloProvider来提供Apollo客户端实例。
这样做可以通过React的状态管理来记录和更新值,并且可以在需要时对其进行操作。