当组件被销毁时,我想退订事件。
我不确定我是否以适当的方式这样做?
async componentDidMount() {
const claimNumber = 'T1339838'
const {
runtime
} = this.context
const data = await runtime.select('comments-get', {
claimNumber: claimNumber
})
this.setState({
commentsData: data
})
const commentsUpdated = runtime.fb.ref('/comments')
commentsUpdated.on('value', childSnapshot => {
this.updateComments(childSnapshot.val())
})
}
componentWillUnmount() {
// TODO: Remove on listener
window.removeEventListener('resize', this.commentsUpdated)
}
答案 0 :(得分:2)
window.removeEventListener仅应在将事件侦听器添加到窗口对象时使用。例如,如果要使用以下代码添加事件侦听器:
//添加一个侦听器
window.addEventListener('resize', this.commentsUpdated);
然后,在componentWillUnmount中,必须使用以下代码删除事件侦听器:
componentWillUnmount() {
// TODO: Remove on listener
window.removeEventListener('resize', this.commentsUpdated)
}
在上述情况下,只需清空或为this.commentsUpdated分配null即可。