我想在组件被销毁时取消订阅事件。
我不确定我是否以正确的方式这样做?
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)
}
最佳答案
仅当事件监听器添加到窗口对象时才应使用window.removeEventListener。例如,如果您使用以下代码添加事件监听器:
//添加监听器
window.addEventListener('resize', this.commentsUpdated);
然后,在 componentWillUnmount 中,必须使用以下代码删除事件监听器:
componentWillUnmount() {
// TODO: Remove on listener
window.removeEventListener('resize', this.commentsUpdated)
}
在上述情况下,只需清空或将 null 分配给 this.commentsUpdated 即可。
关于javascript - 这是如何取消订阅 react 中的事件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52667421/