使用React Apollo如何不调用refetch每3秒更新进度条user.percent值
调整方案
Apollo Client 内置的 useQuery 本身提供轮询能力,不需要手动调用 refetch 结合定时器实现,直接通过 pollInterval 配置项指定轮询间隔即可,调整后代码如下:
import { useParams } from 'react-router-dom'; const ProgressBar = () => { const { userId } = useParams<{userId: string}>(); const { data: { user = null } = {} } = useUserQuery({ variables: { uuid: userId }, skip: !userId, // 新增轮询配置,单位为毫秒 pollInterval: 3000, }); if (!user) return null; return <p>{user.percent}</p> }
方案优势
- 无需额外引入第三方 interval 相关 Hooks,减少项目依赖
- 自动适配
skip逻辑:userId为空时轮询会自动暂停,不会发起无效请求 - 内置组件卸载自动停止轮询逻辑,不会出现内存泄漏问题
- 自动合并重复请求,避免网络卡顿场景下请求积压
如果需要根据业务逻辑动态启停轮询,比如进度到100%后停止轮询,可以调用 useQuery 返回的 startPolling 和 stopPolling 方法实现,示例如下:
import { useEffect } from 'react'; import { useParams } from 'react-router-dom'; const ProgressBar = () => { const { userId } = useParams<{userId: string}>(); const { data: { user = null } = {}, startPolling, stopPolling } = useUserQuery({ variables: { uuid: userId }, skip: !userId, }); useEffect(() => { if (!userId) return; // 组件挂载且userId存在时启动轮询 startPolling(3000); return () => stopPolling(); }, [userId, startPolling, stopPolling]); useEffect(() => { // 进度到100%时停止轮询 if (user?.percent === 100) { stopPolling(); } }, [user?.percent, stopPolling]); if (!user) return null; return <p>{user.percent}</p> }
内容的提问来源于stack exchange,提问作者user15375616
相关产品推荐
相关产品推荐

