简体   繁体   English

在 React Native 中没有移除事件监听器

[英]Event listener is not removed in React Native

I have registered an event for handling the hardware back button press in the Home Screen .我已经注册了一个事件来处理Home Screen中的硬件后退按钮按下。 Whenever I click the back button when I am in the home screen , it will ask me for the exit confirmation alert box.每当我在主屏幕单击后退按钮时,它都会询问我退出确认警报框。 I want this behaviour to happen only in the Home screen , not in any other screen.我希望这种行为只发生在主屏幕上,而不是在任何其他屏幕上。 When I am in some other screen, let's say Setting Screen and I click the back button, it still shows me the exit confirmation alert box.当我在其他屏幕中时,比如说设置屏幕,然后单击后退按钮,它仍然显示退出确认警报框。 It seems like the event I registered on the Home Screen has not been removed.我在主屏幕上注册的事件似乎没有被删除。

const backAction = () => {
    Alert.alert('Close the KhataBook app?', 'Are you sure you want to exit?', [
      {
        text: 'Cancel',
        onPress: () => null,
        style: 'cancel',
      },
      {text: 'YES', onPress: () => BackHandler.exitApp()},
    ]);
    return true;
  };

  useEffect(() => {
    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      backAction,
    );
    return () => backHandler.remove();
  }, []);

Try to remove listener like in docs, with removeEventListener method尝试使用 removeEventListener 方法删除文档中的侦听器


  useEffect(() => {
    BackHandler.addEventListener("hardwareBackPress", backAction);

    return () =>
      BackHandler.removeEventListener("hardwareBackPress", backAction);
  }, []);

If you are using react navigation you can achieve that by doing the following:如果您使用的是反应导航,您可以通过执行以下操作来实现:

  useFocusEffect(() => {
        const backHandler = BackHandler.addEventListener(
            'hardwareBackPress', ()=>{ navigation.goBack(); return true; });
        return () => {
            backHandler.remove();
        };
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM