【问题标题】:React Navigation - create confirmation screen before exiting appReact Navigation - 在退出应用程序之前创建确认屏幕
【发布时间】:2021-03-15 05:16:54
【问题描述】:

我使用react-nativereact-navigation(v5),在Android上,返回按钮会弹出每个屏幕,直到没有更多屏幕,然后退出应用程序。

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

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() 总是返回 false,以及是否真的有办法检查剩下多少屏幕?

【问题讨论】:

  • 在你的代码中你说canGoBack总是返回false,在你的问题中你说它总是返回true。你是指哪一个?它应该只在第一个屏幕上返回false,否则返回true
  • 无论屏幕如何,它总是返回 false,抱歉打错了..

标签: android react-native react-navigation react-navigation-v5


【解决方案1】:
  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);
    }, []),
  );

这段代码确实对我有用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 2019-07-08
    • 2018-01-12
    • 1970-01-01
    相关资源
    最近更新 更多