反应如何在组件中正确删除列表器将卸载,为什么我需要在构造函数中绑定
React how to remove listners correctly in componentWillUnmount, why do I need the bind in the constructor?
我有点困惑,这个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:
bind() 方法创建一个新函数,该函数在调用时将其 this 关键字设置为提供的值,并在调用新函数时提供的任何参数序列之前具有给定的参数序列。
您的第一种方法使用新的绑定函数覆盖this.togglePaneHelper
。第二个删除了与添加的不同事件侦听器函数 - addEventListener
和removeEventListener
都必须获得相同的函数引用。
相关文章:
- 我是否可以检测到javascript正在被卸载(作为调试模式)
- 动态加载和卸载js文件
- 在页面卸载时写入HTML5 FileSystem API存储
- 如何禁用窗口.当计时器超时时,打开卸载警报
- 从jqueryajax加载php页面卸载当前页面
- 火灾在卸载前确认警报仅适用于外部站点
- 在火狐浏览器卸载之前
- 在窗口中单击按钮完成之前,光标不会停止.请继续卸载
- 卸载未触发组件WillUnmount的子级
- ReacJS与猴面包树,如何在卸载组件后释放光标
- 避免重新评估和动态卸载用“require”调用的对象
- 我可以't在Chrome中触发卸载事件
- Modernizr IE跳过“;卸载”;
- 在AngularJS中手动加载和卸载外部javascript
- 有没有一种方法可以为卸载的lazylod图像隐藏alt标签
- 从模态卸载数据
- 页面卸载期间的JavaScript事件循环
- 为什么没有收到从(之前)卸载事件发送的 POST 数据
- 反应如何在组件中正确删除列表器将卸载,为什么我需要在构造函数中绑定
- 反应为什么卸载组件很慢