我尝试使用以下代码在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
方法。是否有删除事件侦听器的优雅方法。任何帮助将不胜感激。
答案 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);
}
}