2016-02-05 42 views
6

我有点糊涂了,就是这个sintax之间的区别:反应如何正确删除componentWillUnmount中的列表,为什么我需要在构造函数中的绑定?

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. 

回答

11

重要:

a.bind(this) !== a.bind(this) 

根据MDN

绑定()方法创建一个新的功能,调用它时,具有其将此关键字设置为所提供的值,具有的参数在给定序列在调用新函数时提供的任何之前。

您的第一种方法用新的绑定函数覆盖this.togglePaneHelper。第二个删除不同的事件监听器功能比它添加 - addEventListenerremoveEventListener必须得到相同的参考的功能。

+0

因此,第一种方法是正确删除事件侦听器的方法?对这篇文章的任何评论:https://gist.github.com/Restuta/e400a555ba24daa396cc? – claireablani

+0

是的,第一种方法按预期工作 - 就像它在该要点中讨论的一样。 –

相关问题