[英]How to avoid multiple event listeners from being attached?
Is the following code going to attach multiple event listeners or will React Native / expo-linking only allow one event listener be attached at a time?以下代码是要附加多个事件侦听器还是 React Native / expo-linking 一次只允许附加一个事件侦听器?
import * as Linking from 'expo-linking'
import { useIsFocused } from '@react-navigation/native'
const MyComponent = () => {
const isFocused = useIsFocused()
useEffect(() => {
fetchData()
Linking.addEventListener('url', _handleEvent)
}, [isFocused])
const fetchData = () => {
// ...
}
const _handleEvent = () => {
// ...
}
return (
<View><View>
)
}
Is there are a way to check if an event listener already exists so I can do something like:有没有办法检查事件侦听器是否已经存在,以便我可以执行以下操作:
useEffect(() => {
fetchData()
if(!eventListenerExists){
Linking.addEventListener('url', _handleEvent)
}
}, [isFocused])
It'll attach multiple handlers, adding one each time isFocused
changes.它将附加多个处理程序,每次isFocused
更改时添加一个。 To remove the previous handler when attaching the next, return a function that React will call:要在附加下一个处理程序时删除前一个处理程序,请返回一个 React 将调用的函数:
useEffect(() => {
fetchData()
Linking.addEventListener('url', _handleEvent)
return () => Linking.removeEventListener('url', _handleEvent) // <======
}, [isFocused])
You want to do that anyway so that the handler is removed when your component is completely unmounted.您无论如何都想这样做,以便在您的组件完全卸载时删除处理程序。
This is covered in the React documentation here .这在此处的 React 文档中有所介绍。
I think even should call one time我想甚至应该打一次电话
useEffect(() => {
Linking.addEventListener('url', _handleEvent)
return () => Linking.removeEventListener('url', _handleEvent) // <======
}, [])
1、in the useEffect callback, return the function that remove the listener; 1、在useEffect回调中,返回移除监听器的函数; 2、every time remove the listener before bind it. 2、每次在绑定之前删除监听器。 such as:如:
useEffect(() => {
window.removeEventListener('url', hander);
window.addEventListener('url', hander);
return () => window.removeEventListener('url', hander);
}, [XXX])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.