我有一个带有两个事件侦听器的 React Native 组件,用于链接和动态链接,如何使用钩子取消订阅?
useEffect(() => {
// Update the document title using the browser API
if (Platform.OS === "ios") {
SecurityScreen.enabled(true);
}
// global.perra = "a";
usingAlternativeAPI();
Linking.addEventListener("url", deepLinkHandler);
const unsubscribe = dynamicLinks().onLink(handleDynamicLink);
// When the component is unmounted, remove the listener
return () => unsubscribe();
}, []);
答案 0 :(得分:2)
链接库有一个 removeEventListener() 函数,您可以通过传递 url 事件类型和处理程序调用。此代码应该可以工作。
useEffect(() => {
// useEffect code here
return function cleanup() {
unsubscribe();
Linking.removeEventListener("url", deepLinkHandler);
};
}, []);
答案 1 :(得分:1)
你以前试过这个吗?
useEffect(() => {
// Update the document title using the browser API
if (Platform.OS === "ios") {
SecurityScreen.enabled(true);
}
// global.perra = "a";
usingAlternativeAPI();
const un = Linking.addEventListener("url", deepLinkHandler);
const unsubscribe = dynamicLinks().onLink(handleDynamicLink);
// When the component is unmounted, remove the listener
return () => {
unsubscribe();
un()
}
}, []);