javascript – reactjs事件监听器beforeunload已添加但未删除

我有一个反应组件,如:

import React, { PropTypes, Component } from 'react'


class MyComponent extends Component {

    componentDidMount() {
       window.addEventListener("beforeunload", function (event) {
            console.log("hellooww")
            event.returnValue = "Hellooww"
        })
    }

    componentWillUnmount() {
        window.removeEventListener("beforeunload", function (event) {
            console.log("hellooww")
            event.returnValue = "Hellooww"
        })
    }

    render() {

        return (
            <div>
                Some content
            </div>
        )
    }

}

export default MyComponent

此处将事件列表器添加到组件中.当我刷新页面时,它会弹出要求离开页面.

但当我转到另一个页面并刷新它再次显示相同的弹出窗口.

我正在从componentWillUnmount上的组件中删除eventListener.那为什么它没有被删除?

如何在其他页面上删除beforeunload事件?

解决方法:

removeEventListener应该获得对addEventListener中分配的相同回调的引用.重新创建功能是行不通的.解决方案是在其他地方创建回调(在此示例中为onUnload),并将其作为对addEventListener和removeEventListener的引用传递:

import React, { PropTypes, Component } from 'react'


class MyComponent extends Component {
    constructor(props) {
        super(props);

        this.onUnload = this.onUnload.bind(this); // if you need to bind callback to this
    }

    onUnload(event) { // the method that will be used for both add and remove event
        console.log("hellooww")
        event.returnValue = "Hellooww"
    }

    componentDidMount() {
       window.addEventListener("beforeunload", this.onUnload)
    }

    componentWillUnmount() {
        window.removeEventListener("beforeunload", this.onUnload)
    }

    render() {

        return (
            <div>
                Some content
            </div>
        )
    }

}

export default MyComponent
上一篇:使用addKeyListener绑定密钥Javascript


下一篇:JavaScript回调函数中的变量总是在循环中获得最后一个值?