如何使用 useQuery 和 subscribeToMore 取消订阅 [英] how to unsubscribe with useQuery and subscribeToMore
问题描述
另一篇博文分享了如何取消订阅的示例,其中Apollo docs 没有.Apollo 文档确实提到了 subscribeToMore 返回的内容......
Another post shared an example of how to unsubscribe, where the Apollo docs don't. The Apollo docs do mention what subscribeToMore returns...
subscribeToMore
:设置订阅的函数.subscribeToMore
返回一个可用于取消订阅的函数.
subscribeToMore
: A function that sets up a subscription.subscribeToMore
returns a function that you can use to unsubscribe.
这确实给出了一个提示.看个例子会很有帮助.
This does give a hint. It would help to see an example.
在 useEffect()
内部使用 @apollo/react-hooks
并返回 subscribeToMore
的结果,是这样吗取消订阅组件卸载?
Using @apollo/react-hooks
, inside of a useEffect()
and returning the results of the subscribeToMore
, is this the way to unsubscribe on a component unmount?
const { data, error, loading, subscribeToMore } = useQuery(GET_DATA)
useEffect(() => {
const unsubscribe = subscribeToMore(/*...*/)
return () => unsubscribe();
}, [])
推荐答案
当组件卸载时,应该为您取消任何关联的订阅.除非您想在此之前取消订阅,否则您不必手动管理它.
Any associated subscriptions should be unsubscribed for you when the component unmounts. You shouldn't have to manually manage it unless you want to unsubscribe before then.
当 subscribeToMore
被调用时,您可以看到订阅正在被跟踪 此处 然后在查询被清理时取消订阅 这里.
You can see the subscription being tracked when subscribeToMore
is called here and then unsubscribed when the query is being cleaned up here.
这篇关于如何使用 useQuery 和 subscribeToMore 取消订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!