【发布时间】:2021-03-15 05:16:54
【问题描述】:
我使用react-native和react-navigation(v5),在Android上,返回按钮会弹出每个屏幕,直到没有更多屏幕,然后退出应用程序。
我想阻止退出并在退出应用程序之前提示用户是|否,但检查 navigation.state 或 canGoBack 并没有指出退出前有关最终屏幕的任何线索
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