2017-06-05 53 views
1

我有反應組件,我使用componentDidMount生命週期鉤綁定mousedown事件到文檔。當鼠標向下事件觸發時,我綁定兩個更多的事件mousemovemouseup文檔也我刪除這些事件在mouseup事件。document.removeEventListner無法刪除事件中的反應

我的問題是當mouseup事件觸發它假設刪除mousemovemouseup但它不工作。相反,每次我點擊頁面mouseup觸發多次,如:1,3,6,10,15 ...它的倍增。

componentWillUnmount也沒有從文件刪除事件。

import React, { Component } from 'react' 

class SandBox extends Component{ 
    componentDidMount(){ 
     document.addEventListener('mousedown', this.mouseDown.bind(this)) 
    } 

    //mouseDown 
    mouseDown(){ 
     document.addEventListener('mouseup', this.mouseUp.bind(this)) 
     document.addEventListener('mousemove', this.mouseMove.bind(this)) 
    } 

    //mouseUp 
    mouseUp(){ 
     // this is not removing the events from document 
     document.removeEventListener('mouseup', this.mouseUp, false) 
     document.removeEventListener('mousemove', this.mouseMove, false) 
     // this triggers 1,3,6,10,15 times 
     console.log('mose up') 
    } 

    moseMove(){ 
     // mosemoveCodes 
    } 

} 
+0

使用forceUpdate也許? –

+0

的可能的複製[功能卸載,但是,事件偵聽仍在執行(https://stackoverflow.com/questions/44133311/function-unmounted-but-still-executing-on-eventlistener) – duwalanise

+1

@duwalanise它不是同樣的問題,我問題是我不能刪除事件。這個問題是事件組件卸載後觸發。 –

回答

1

當你bind的功能它將使新功能,你不能老參考this.whatever這就是爲什麼removeEventlistener無法找到您的功能。你可以使用es6 classconstructor來解決這個問題。

class YourComponent extends Component { 
    constructor(props){ 
    super(props) 
    //bind and reference your methods here 
    this.mouseDown = this.mouseDown.bind(this) 
    this.mouseUp = this.mouseUp.bind(this) 
    this.mouseMove = this.mouseMove.bind(this) 
    // now its pointing corectcly 
    } 
    // lifecycle 
    componentDidMount(){ 
    document.addEventListener('mousedown', this.mouseDown.bind(this)) 
    } 
    //mouseDown 
    mouseDown(){ 
    document.addEventListener('mouseup', this.mouseUp) 
    document.addEventListener('mousemove', this.mouseMove) 
    } 

    //mouseUp 
    mouseUp(){ 
    // this is will work 
    document.removeEventListener('mouseup', this.mouseUp, false) 
    document.removeEventListener('mousemove', this.mouseMove, false) 

    console.log('mouse up') 
    } 
    // unmount 
    componentWillUnmount(){ 
    // this is will work 
    document.removeEventListener('mousedown', this.mouseDown, false) 
    } 
}