首页 > 解决方案 > React Navigation - 在退出应用程序之前创建确认屏幕

问题描述

我正在使用react-nativeand react-navigation(v5),在 Android 上,后退按钮将弹出每个屏幕,直到没有更多屏幕并退出应用程序。

我想阻止退出并在退出应用程序之前用 yes|no 提示用户,但在退出之前检查navigation.stateorcanGoBack并没有指出有关最终屏幕的任何线索

BackHandler.addEventListener('hardwareBackPress', () => {
    const canGoBack = navigation.canGoBack(); // always false
    const isFocused = navigation.isFocused(); // always true

    // TODO: how to check if we're on last screen?
    // I need to pop until last screen and display confirmation alert
    // navigation.state is a whole bunch of whores with no reliable way to check for last screen (I tried the _index_ and _history_

    if ( canGoBack && isFocused ) {
        navigation.goBack(); // never goes here
        return true; // means handled, default behaviour of popping screen won't be executed
    }
    return false; // not handled, react-navigation will pop screens and when no more screens to pop, will exit app
    // return true; // if I return true, no screens will get popped, and no auto-exit app also, but I need the pop until last
}

有谁知道为什么navigation.canGoBack()总是返回假,如果真的有办法检查剩下多少屏幕?

标签: androidreact-nativereact-navigationreact-navigation-v5

解决方案


  useFocusEffect(
    React.useCallback(() => {
      const onBackPress = () => {
        Alert.alert('Are you sure', 'Do you really want to exit?', [
          {
            text: 'Cancel',
            onPress: () => null,
            style: 'cancel',
          },
          {text: 'YES', onPress: () => BackHandler.exitApp()},
        ]);
        return true;
      };

      BackHandler.addEventListener('hardwareBackPress', onBackPress);

      return () =>
        BackHandler.removeEventListener('hardwareBackPress', onBackPress);
    }, []),
  );

这段代码确实对我有用


推荐阅读