我有点困惑,这个sintax有什么区别:
constructor(props) {
super(props);
this.state = {
openPane: false
}
this.togglePaneHelper = this.togglePaneHelper.bind(this);
}
componentDidMount() {
document.body.addEventListener('click', this.togglePaneHelper);
}
componentWillUnmount() {
document.body.removeEventListener('click', this.togglePaneHelper);
}
还有这个:
constructor(props) {
super(props);
this.state = {
openPane: false
}
}
componentDidMount() {
document.body.addEventListener('click', this.togglePaneHelper.bind(this));
}
componentWillUnmount() {
document.body.removeEventListener('click', this.togglePaneHelper);
}
我担心的是第二种语法没有正确删除监听器,它导致了这个警告:
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.
最佳答案
重要提示:
a.bind(this) !== a.bind(this)
根据 MDN :
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
您的第一种方法使用新的绑定(bind)函数覆盖 this.togglePaneHelper
。第二个删除了与添加时不同的事件监听器函数 - addEventListener
和 removeEventListener
必须获得相同的函数引用。
关于javascript - React 如何在 componentWillUnmount 中正确移除监听器,为什么我需要在构造函数中绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35223918/