2016-02-05 1 views
6

componentWillUnmountでlistenerを正しく削除する方法に反応します。なぜコンストラクタでバインドが必要ですか?私は少し困惑している、この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); 
    } 

と、この1:

constructor(props) { 
    super(props); 
    this.state = { 
     openPane: false 
    } 
    } 
    componentDidMount() { 
    document.body.addEventListener('click', this.togglePaneHelper.bind(this)); 
    } 
    componentWillUnmount() { 
    document.body.removeEventListener('click', this.togglePaneHelper); 
    } 

私の関心は、2番目の構文が正しくのリスナーを削除していないということで、

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

重要:

それは、この警告を引き起こします MDNによると
a.bind(this) !== a.bind(this) 

バインド()メソッドが呼び出された場合、そのキーワードこの引数の指定された配列と、与えられた値に設定された、新しい機能を作成します新しい関数が呼び出されたときに提供されているものの前に

最初の方法は、新しいバインドされた機能でthis.togglePaneHelperをオーバーライドします。 2つ目は、追加されたものとは異なるイベントリスナー機能を削除します。addEventListenerremoveEventListenerは同じ機能を持つ参照を取得する必要があります。

+0

最初のアプローチは、イベントリスナーを正しく削除する方法ですか?この記事に対するコメント:https://gist.github.com/Restuta/e400a555ba24daa396cc? – claireablani

+0

はい、最初のアプローチは、その要点で議論されているのと同じです。 –

関連する問題