这个问题可能出现在Apollo客户端有任何突变操作的情况下,当应用程序处于离线状态时。为了解决这个问题,可以使用Apollo提供的缓存API进行缓存管理,这样无论应用程序在线还是离线,都可以根据最新的状态正确地更新查询结果。
以下是通过使用缓存API更新缓存来解决该问题的示例代码:
import { useQuery } from '@apollo/react-hooks';
import { gql } from 'apollo-boost';
import { useApolloClient } from '@apollo/react-hooks';
const GET_USERS = gql`
query getUsers {
users {
id
name
}
}
`;
function Users() {
const client = useApolloClient();
const { loading, error, data } = useQuery(GET_USERS);
if (loading) return 'Loading...';
if (error) return `Error! ${error.message}`;
return (
{data.users.map(user => (
{user.name}
))}
);
}
在上面的代码中,我们使用了useApolloClient
钩子来访问缓存API,并在添加新用户之后更新缓存数据。这样,无论我们是在线还是离线,都