问题描述
另一个帖子分享了如何取消订阅的示例,其中<一个href ="https://www.apollograph ql.com/docs/reacect/api/reacect-hooks/#usequery"rel ="noreferrer"> apollo docs not. apollo文档提及了什么子命令返回...
subscribeToMore:设置订阅的函数. subscribeToMore返回可以用于取消订阅的函数.
这确实给了一个提示.它有助于看到一个例子.
问题
使用@apollo/react-hooks,在useEffect()的内部并返回subscribeToMore的结果,这是在组件上取消订阅的方式?
const { data, error, loading, subscribeToMore } = useQuery(GET_DATA) useEffect(() => { const unsubscribe = subscribeToMore(/*...*/) return () => unsubscribe(); }, [])
推荐答案
在组件卸载时,任何相关的订阅都应为您取消订阅.除非您希望在那之前取消订阅,否则不得不手动管理它.
当subscribeToMore称为https://github.com/apollographql/apollo -client/blob/155536f26C335A2242F26C335A2242F24E2/SRC/CORE/OBServableSquery.ts#l385"rel =在这里然后在清除查询这里.
其他推荐答案
subscribetomore返回取消订阅函数,因此您的代码是正确的.
https://github.com/apollographql/apollo-client/issues/5245
问题描述
Another post shared an example of how to unsubscribe, where the Apollo docs don't. The Apollo docs do mention what subscribeToMore returns...
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.
the question
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.
You can see the subscription being tracked when subscribeToMore is called here and then unsubscribed when the query is being cleaned up here.
其他推荐答案
SubscribeToMore returns the unsubscribe function, so your code is correct.