2017-09-24 39 views
0

我正在使用React Navigation,并且当按下后退按钮时我需要一些自定义功能。这里是我的代码:React Native BackHandler不移除事件监听器

class AddEditIngredient extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     editStarted: false 
    }; 
    this.goBack =() => { 
     if (this.state.editStarted === true) { 
     Alert.alert(
      "Ingredient Not Saved", 
      "Do you want to navigate away without saving ingredient?", 
      [ 
      { text: "Cancel", onPress:() => null, style: "cancel" }, 
      { text: "Yes", onPress:() => this.props.navigation.goBack() } 
      ], 
      { cancelable: true } 
     ); 
     } else { 
     this.props.navigation.goBack(); 
     } 
    }; 
} 

componentWillMount() { 
    BackHandler.addEventListener("hardwareBackPress", this.goBack); 
} 

componentWillUnmount() { 
    BackHandler.removeEventListener("hardwareBackPress", this.goBack); 
} 

我GoBack的功能工作正常,屏幕上的后退按钮,但是当我尝试按物理后退按钮使其弹出所有的屏幕和应用程序最小化。从我读过的关于这个问题的前几篇文章中可以看出,removeEventListener并没有引用与addEventListener相同的函数。所以我试过这个:

constructor(props) { 
    super(props); 
    this.state = { 
     editStarted: false 
    }; 
    this.goBack = this.goBack.bind(this); 
} 
goBack =() => { 
     if (this.state.editStarted === true) { 
     Alert.alert(
      "Ingredient Not Saved", 
      "Do you want to navigate away without saving ingredient?", 
      [ 
      { text: "Cancel", onPress:() => null, style: "cancel" }, 
      { text: "Yes", onPress:() => this.props.navigation.goBack() } 
      ], 
      { cancelable: true } 
     ); 
     } else { 
     this.props.navigation.goBack(); 
     } 
    }; 

但它没有奏效。任何人都可以指出我的错误吗?

感谢

回答

0

终于找到了答案this post。我需要在我的goBack函数结束时返回true,以表明返回行为已被处理。