在 Apollo React 中,subscribeToMore
方法用于订阅新的数据更新。如果你发现 subscribeToMore
不会更新数据,可能是由于以下原因之一:
缺少 updateQuery
函数:subscribeToMore
需要提供一个 updateQuery
函数,以便在接收到新数据时更新缓存。这个函数将接收先前查询的结果和订阅到的新数据,然后返回一个更新后的查询结果。确保在你的代码中提供了 updateQuery
函数。
缓存问题:Apollo 使用缓存来存储查询结果,以便在需要时快速检索。如果你的数据更新没有在缓存中更新,subscribeToMore
也就无法获取到最新的数据。确保你的查询结果在缓存中正确更新。
下面是一个示例代码,演示如何使用 subscribeToMore
来更新数据:
import { useQuery } from '@apollo/client';
import { gql } from 'apollo-boost';
const GET_MESSAGES = gql`
query GetMessages {
messages {
id
content
}
}
`;
const SUBSCRIBE_TO_MESSAGES = gql`
subscription SubscribeToMessages {
newMessage {
id
content
}
}
`;
const Messages = () => {
const { loading, error, data, subscribeToMore } = useQuery(GET_MESSAGES);
useEffect(() => {
subscribeToMore({
document: SUBSCRIBE_TO_MESSAGES,
updateQuery: (prev, { subscriptionData }) => {
if (!subscriptionData.data) return prev;
const newMessage = subscriptionData.data.newMessage;
return Object.assign({}, prev, {
messages: [...prev.messages, newMessage],
});
},
});
}, [subscribeToMore]);
if (loading) return Loading...
;
if (error) return Error :(
;
return (
{data.messages.map((message) => (
{message.content}
))}
);
};
export default Messages;
在上述示例中,subscribeToMore
方法在组件挂载后被调用,用于订阅 newMessage
订阅源的更新。在 updateQuery
函数中,我们将新的消息添加到先前的查询结果中,并返回一个新的查询结果。这样,每当有新消息时,Apollo 将自动更新组件中的数据。