首页 > react中 怎么在componentWillUnmount中使用removeEventListener

react中 怎么在componentWillUnmount中使用removeEventListener

我在componentDidMount中,给window添加了一个scroll事件:srocll1
我现在想在componentWillUnmount中删除这个事件,这该怎么写呢?

简要代码:

export default class A extends React.Component {

    constructor(props) {
        super(props);
    }
    scroll1(){}

    componentDidMount() {
        window.addEventListener('scroll', this.srcoll1.bind(this));
    }
    
    componentWillUnmount(){
        window.removeEventListener('scroll', this.srcoll1);

    }

    render() {
    };

}

这个写法可以成功给给window加上事件,然后Ummount时,这个事件删不掉。求大神告知正确的写法,感激不尽!!!


export default class A extends React.Component {

    constructor(props) {
        super(props);
        this.scroll1 = this.scroll1.bind(this)
    }
    scroll1(){}

    componentDidMount() {
        window.addEventListener('scroll', this.scroll1);
    }
    
    componentWillUnmount(){
        window.removeEventListener('scroll', this.scroll1);

    }

    render() {
    };

}

因为你绑定的是this.scroll1.bind(this),而不是this.scroll1,所以需要将this.scroll1.bind(this)指到同一个变量
另外airbnb的react guide也是建议用这种写法
https://github.com/JasonBoy/javascript/tree/master/react#methods-%E5%87%BD%E6%95%B0

当在 render() 里使用事件处理方法时,提前在构造函数里把 this 绑定上去.
为什么? 在每次 render 过程中, 再调用 bind 都会新建一个新的函数,浪费资源.

【热门文章】
【热门文章】