如何在React Native中为react-native-tts异步功能删除事件监听器

时间:2019-10-16 22:52:06

标签: reactjs react-native

我尝试使用以下代码在componentWillUnmount生命周期方法中删除事件侦听器:

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.subscription = Tts.addEventListener('tts-finish', this._startRecognition.bind(this));
  }

  componentWillMount() {
    Tts.speak('Welcome to Hello World');
  }

  _startRecognition() {
    console.log('==================== recognizing text that was spoken ====================');
  }

  componentWillUnmount() {
    Tts.removeEventListener('tts-finish');
  }
}

当我再次打开该组件时,它将启动_startRecognition方法。是否有删除事件侦听器的优雅方法。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以尝试以下吗?

class MyComponent extends Component {
  constructor(props) {
    super(props);
  }

  componentWillMount() {
    Tts.speak('Welcome to Hello World');
    Tts.addEventListener('tts-finish', this._startRecognition)
  }

  _startRecognition() {
    console.log('==================== recognizing text that was spoken ====================');
  }

  componentWillUnmount() {
    Tts.removeEventListener('tts-finish', this._startRecognition);
  }
}