[英]Unsubscribe subscription in Apollo Client
In my component, I have this code: 在我的组件中,我有这个代码:
componentDidMount () {
// Setup subscription listener
const { client, match: { params: { groupId } } } = this.props
client.subscribe({
query: HOMEWORK_IN_GROUP_SUBSCRIPTION,
variables: { groupId },
}).subscribe({
next ({ data }) {
const cacheData = client.cache.readQuery({
query: GET_GROUP_QUERY,
variables: { groupId },
})
const homeworkAlreadyExists = cacheData.group.homeworks.find(
homework => homework._id == data.homeworkInGroup._id
)
if (!homeworkAlreadyExists) {
client.cache.writeQuery({
query: GET_GROUP_QUERY,
variables: { groupId },
data: { ...cacheData,
group: { ...cacheData.group,
homeworks: [ ...cacheData.group.homeworks,
data.homeworkInGroup,
],
},
},
})
}
},
})
}
The problem is that this component will re-subscribe when mounted and will mantain subscribed even if unmounted. 问题是这个组件在安装时会重新订阅,即使卸载也会保留订阅。
How can I unsubscribe my component? 如何取消订阅我的组件?
client.subscribe({ ... }).subscribe({ ... })
will return an instance for your subscription, that you can use to unsubscribe. client.subscribe({ ... }).subscribe({ ... })
将返回您订阅的实例,您可以使用该实例取消订阅。
So something like: 所以类似于:
componentDidMount () {
// Setup subscription listener
// (...)
this.querySubscription = client.subscribe({
// (...)
}).subscribe({
// (...)
})
}
componentWillUnmount () {
// Unsibscribe subscription
this.querySubscription.unsubscribe();
}
You can get some inspiration by looking at how react-apollo manages this situation looking at their code base. 您可以通过查看react-apollo如何管理这种情况来查看其代码库来获得灵感。
NOTE: My best advice would be to use Subscription component, that will manage everything for you. 注意:我最好的建议是使用Subscription组件,它将为您管理一切。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.