更改应用程序状态后的BackHandler不会调用预订的函数

时间:2018-08-07 16:54:54

标签: react-native

复制步骤:

  1. 按下家用硬件按钮(应用程序状态更改为后台)
  2. 打开应用并尝试按返回按钮

预期结果:handleBackButtonClick被调用
     实际结果:没有调用handleBackButtonClick

我的代码:

import { BackHandler } from 'react-native';

componentWillMount() {
    AppState.addEventListener('change', this.handleAppStateChange);
}

componentWillUnmount() {
    AppState.removeEventListener('change', this.handleAppStateChange);
}

handleAppStateChange = (state: AppStateStatus) => {
    if (state === 'active') {
        console.log('LISTEN');
        BackHandler.addEventListener('hardwareBackPress', this.onBackPress);
    } else {
        console.log('UNLISTEN');
        BackHandler.removeEventListener('hardwareBackPress', this.onBackPress);
    }
};

handleBackButtonClick = () => {
    console.log('press back')
    this.props.navigation.goBack(null);
    return true;
}

1 个答案:

答案 0 :(得分:0)

我有点不确定您要完成什么,但是基于BackHandler上的本机文档,您可能需要将eventListener放在componentDidMount上以确保安全。然后,您的处理程序通常会决定如何退回例如

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

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

  handleBackPress = () => {
    this.goBack(); // works best when the goBack is async
    return true;
  }

此外,除非在您的上下文中另外定义,this.onBackPress就是undefined