如何用React与apollo-link-state每2秒轮询客户端缓存数据
嘿,我来帮你搞定这个纯客户端轮询本地缓存的问题!其实Apollo Client的查询配置本身就支持轮询,而且因为你的查询是带@client指令的,轮询的时候只会读取本地缓存,不会发起任何服务端请求,完全符合你的需求。
接下来分两种组件类型给你具体的实现方案:
1. 函数组件(使用Hooks)
如果你用的是React函数组件,直接用useQuery Hook,只需要在配置里加上pollInterval: 2000就可以了,代码示例如下:
import { useQuery, useEffect } from '@apollo/client'; import { GET_NOTIF_LIST } from './path-to-your-queries'; function NotificationComponent() { // 配置pollInterval为2000毫秒(每2秒轮询一次) const { loading, error, data, stopPolling } = useQuery(GET_NOTIF_LIST, { pollInterval: 2000, }); // 可选:组件卸载时停止轮询,避免不必要的资源消耗 useEffect(() => { return () => stopPolling(); }, [stopPolling]); if (loading) return <div>加载中...</div>; if (error) return <div>出错了:{error.message}</div>; const notifications = data.notificationsState?.notifications || []; return ( <div className="notifications"> {notifications.map(notify => ( <div key={notify.uid} className={`notification-${notify.type}`}> <h4>{notify.title}</h4> <p>{notify.message}</p> </div> ))} </div> ); }
2. 类组件(使用高阶组件)
如果你的组件是类组件,就用graphql高阶组件包裹,在options里设置pollInterval:
import React from 'react'; import { graphql } from '@apollo/client/react/hoc'; import { GET_NOTIF_LIST } from './path-to-your-queries'; class NotificationComponent extends React.Component { // 组件卸载时停止轮询 componentWillUnmount() { this.props.data.stopPolling(); } render() { const { loading, error, notificationsState } = this.props.data; if (loading) return <div>加载中...</div>; if (error) return <div>出错了:{error.message}</div>; const notifications = notificationsState?.notifications || []; return ( <div className="notifications"> {notifications.map(notify => ( <div key={notify.uid} className={`notification-${notify.type}`}> <h4>{notify.title}</h4> <p>{notify.message}</p> </div> ))} </div> ); } } // 配置轮询间隔为2秒 export default graphql(GET_NOTIF_LIST, { options: { pollInterval: 2000, }, })(NotificationComponent);
关键说明
- 因为你的查询带了
@client指令,Apollo Client每次轮询时都会直接从本地缓存读取数据,不会向服务端发送任何请求,完全是纯客户端的操作。 - 当你通过
cache.writeQuery、writeData或者apollo-link-state的resolver更新本地缓存中的通知数据时,轮询会自动获取到最新的缓存内容,组件也会随之重新渲染。 - 记得在组件卸载时调用
stopPolling(),避免组件销毁后还继续轮询,造成不必要的资源浪费。
内容的提问来源于stack exchange,提问作者jusus aloha
相关产品推荐
相关产品推荐

