2017-09-24 38 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,以表明返回行爲已被處理。