首页 > 解决方案 > 'hardwareBackPress' 侦听器未在反应原生 android 中的“模糊”事件中删除

问题描述

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

        const backHandler = navigation.addListener('focus', () => {
            BackHandler.addEventListener('hardwareBackPress', backAction);
        });

        const unsubscribeblur = navigation.addListener('blur', () => {
            BackHandler.removeEventListener('hardwareBackPress', _ => {
                console.log('Event listener removed!');
            });
        });

        // Return the function to unsubscribe from the event so it gets removed on unmount

        return () => {
            backHandler.remove();
            unsubscribeblur.remove();
        }
}, [navigation]);

即使添加了一个“模糊”侦听器,删除了“硬件BackPress”侦听器,警报仍然会在其他屏幕上弹出。

标签: androidreact-native

解决方案


模糊时您没有删除 backAction 功能。

const unsubscribeblur = navigation.addListener('blur', () => {
    BackHandler.removeEventListener('hardwareBackPress',  backAction)       });

推荐阅读