我已经在我的主屏幕上的react native应用程序中设置了android后退按钮退出应用程序功能.但当我在其他屏幕上按下android后退按钮时,它也会被调用.

componentDidMount() {

    if (Platform.OS == "android") {
        BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);                           
  }
    this._setupGoogleSignin();           
    this._getUserDetails();
    const { navigate } = this.props.navigation;
    console.log("object url is", this.state.postsArray[0].url);

}

handleBackButton = () => {               
    Alert.alert(
        'Exit App',
        'Exiting the application?', [{
            text: 'Cancel',
            onPress: () => console.log('Cancel Pressed'),
            style: 'cancel'
        }, {
            text: 'OK',
            onPress: () => BackHandler.exitApp()
        }, ], {
            cancelable: false
        }
     )
     return true;
   }
componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
  }

推荐答案

如果在导航到其他屏幕时,主屏幕仍处于安装状态,或者在卸载HomeScreen时,如果不删除EventListener,主屏幕仍将被调用.

您应该在导航或卸载时清除EventListener,

onButtonPress = () => {
  BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
  // then navigate
  navigate('NewScreen');
}

handleBackButton = () => {
 Alert.alert(
     'Exit App',
     'Exiting the application?', [{
         text: 'Cancel',
         onPress: () = > console.log('Cancel Pressed'),
         style: 'cancel'
     }, {
         text: 'OK',
         onPress: () = > BackHandler.exitApp()
     }, ], {
         cancelable: false
     }
  )
  return true;
} 

componentDidMount() {
  BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
}

componentWillUnmount() {
  BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
}

React-native相关问答推荐

我们在react钩子中还需要功能性的 setState 方式吗?

如何在react-native 中从 FlatList 中删除元素/索引?

我可以在状态内有一个函数来响应吗?

如何在 React Native 的嵌套 Touchable 中传播touch 事件?

如何在 React Native 中测量我的应用程序的数据使用情况?

React Native - 初始属性 Android

设置 rootView.appProperties 不会重新渲染根组件

在 react-native 中调试原生 java 代码

如何在 React Native cli 中获取 SHA-1 密钥?

使用像 React Navigation 这样的基于 JS 的导航解决方案优缺点?

React Native - NSNumber 无法转换为 NSString

Error when running watchman

任务在 react-native 中因请求而成为orphaned - 这是什么意思?

> 任务 :app:checkDebugAarMetadata 在运行 react-native run-android 时失败

[React-Native][Jest]SyntaxError: Unexpected token import

React Native Bullet Character? or Unicode?

设置 react-native 元素时使用特定的包名称

列之间的 React Native FlatList 分隔符

Gradlew bundleRelease 不会在 react-native 中生成发布 apk

React Native - 为什么我需要 babel 或 webpack?