因此,我有一个订阅,希望取消订阅:
<DeleteItem
id={item.id}
urlReferer={urlReferer}
subscribeToDeleteItems={() =>
subscribeToMore({
....
}
})
}
>Delete This Item</DeleteItem>
DeleteItem.js
const DeleteItem = props => {
const {urlReferer} = props;
useEffect(() => {
props.subscribeToDeleteItems();
},[urlReferer]);
...
}
...
}
我该怎么做?
答案 0 :(得分:0)
所以我通过调用abortController实现了清理:
useEffect(() => {
const abortController = new AbortController();
props.subscribeToDeleteItems();
return () => {
abortController.abort();
};
},[urlReferer]);
答案 1 :(得分:0)
如果您的效果返回了一个函数,React将在需要清理时运行它。 SubscribeToMore返回取消订阅功能。
const subscribeToNewComments = () =>
subscribeToMore({
document: MESSAGES_SUBSCRIPTION,
variables: { channelId },
updateQuery: (prev, { subscriptionData }) => {
if (!subscriptionData) return prev;
return Object.assign({}, prev, {
channelMessages: [
subscriptionData.data.messageAdded,
...prev.channelMessages,
],
});
},
});
React.useEffect(() => {
let unsub = subscribeToNewComments();
return () => {
unsub();
};
}, [channelId]);