当使用Apollo React的useQuery时,如果缓存工作异常,可以尝试以下解决方法:
import React from 'react';
import { ApolloProvider } from '@apollo/client';
import { ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://example.com/graphql',
cache: new InMemoryCache(),
});
const App = () => {
return (
{/* Your app components */}
);
};
export default App;
import { useQuery, gql } from '@apollo/client';
const GET_DATA = gql`
query GetData($id: ID!) {
// Your query definition
}
`;
const MyComponent = ({ id }) => {
const { loading, error, data } = useQuery(GET_DATA, {
variables: { id },
});
// Rest of your component logic
return (
// Your component UI
);
};
确保查询语句和变量(如果有)与服务器端定义的查询一致。如果查询语句不一致,缓存可能无法正确存储和检索数据。
如果你希望每次组件加载时都强制从服务器获取最新数据,可以在useQuery中设置fetchPolicy为"network-only":
const { loading, error, data } = useQuery(GET_DATA, {
variables: { id },
fetchPolicy: 'network-only',
});
import { useApolloClient } from '@apollo/client';
const MyComponent = () => {
const client = useApolloClient();
const handleDataUpdate = (newData) => {
client.writeQuery({
query: GET_DATA,
variables: { id },
data: newData,
});
};
const handleDataDelete = () => {
client.cache.evict({ id: 'your-data-id' });
};
// Rest of your component logic
return (
// Your component UI
);
};
希望以上解决方法能帮助你解决Apollo React useQuery缓存工作异常的问题。如果问题仍然存在,可以提供更多的代码示例和错误信息,以便更好地帮助你解决问题。