首页 > 解决方案 > 如何在 React Native 中删除 react-native-tts 异步函数的事件监听器

问题描述

我尝试了以下代码来删除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方法。有没有一种优雅的方法来删除事件监听器。任何帮助将不胜感激。

标签: reactjsreact-native

解决方案


你可以试试下面的吗?

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);
  }
}

推荐阅读