返回初始路由后,BackAndroid hardwareBackPress侦听器停止工作

时间:2016-03-30 18:12:01

标签: android react-native

我有一个0.18的React Native应用程序,我正在尝试为Android实现后退按钮功能。我在index.android.js

中有以下代码
let navigator;

BackAndroid.addEventListener('hardwareBackPress', () => {
  if (navigator && navigator.getCurrentRoutes().length > 1) {
    navigator.pop();
    return true;
  }
  return false;
});

在我的渲染中:

<Navigator
    ref={(nav) => { navigator = nav; }}
    ...

如果我前进任意数量的路线,后退按钮会起作用,然后我可以返回任意数量的路线到初始路线。但是,在返回初始路径后,后退按钮将停止工作,直到我重新加载JS或以其他方式重新启动应用程序。

有没有其他人遇到过此问题,解决方案是什么?

编辑:我已经在0.21,0.22和0.23-rc3上进行了测试,并且在最新版本中仍然存在此问题。

1 个答案:

答案 0 :(得分:0)

It appears the issue was that, in other components of the app, we had added event handlers to handle changing layouts on opening the keyboard, and on unmounting these components, we were calling DeviceEventEmitter.removeAllListeners(). Contrary to intuition, this call removes all listeners globally, regardless of the instantiating component, and applies even to listeners instantiated on BackAndroid instead of on DeviceEventEmitter. So, after going back from a component that had a keyboard-toggled layout, the hardwareBackPress listener was also removed and the back button stopped working.

Making the removeAllListeners calls more specific e.g. DeviceEventEmitter.removeAllListeners('keyboardWillShow'); resolved this issue.