在componentWillUnmount中调用时removeEventListener不起作用

ano*_*nym 1 javascript event-listener javascript-events reactjs

我正在尝试setState(),以便在调整窗口大小时在设置为组件状态的不同屏幕尺寸上呈现不同数量的项目。我在组件安装时添加了一个事件侦听器,在卸载时将其删除了。

componentDidMount()
{
    this.updateValue();
    window.addEventListener("resize", this.updateValue.bind(this));
}

updateValue()
{
    var windowWidth = window.screen.width;
    if(windowWidth <= 991 && windowWidth >= 768){
        this.setState({ items:6 })
    } else if(windowWidth <= 767 && windowWidth >= 479){
        this.setState({ items:4 })
    } else if( windowWidth < 480 && windowWidth >= 359){
        this.setState({ items:2 })
    } else if( windowWidth < 360){
        this.setState({ items: 2})
    } else {
        this.setState({items:12})
    }
}

componentWillUnmount()
{
    window.removeEventListener("resize", this.updateValue.bind(this));
}
Run Code Online (Sandbox Code Playgroud)

在安装了组件的路线上工作正常;直到我通过打开另一条路线离开组件并调整窗口的大小(这是我收到错误的时间):

警告:setState(...):只能更新已安装或正在安装的组件。这通常意味着您在未安装的组件上调用了setState()。这是无人值守。请检查FeaturedRestaurants组件的代码。

调整屏幕大小时,每秒我会收到一百个错误。

显然,removeEventListener无法正常工作。我哪里做错了?

小智 6

尝试执行以下操作:

componentDidMount()
{
    this.updateValue();
    window.addEventListener("resize", this.updateValue);
}

updateValue = () =>
{
    var windowWidth = window.screen.width;
    if(windowWidth <= 991 && windowWidth >= 768){
        this.setState({ items:6 })
    } else if(windowWidth <= 767 && windowWidth >= 479){
        this.setState({ items:4 })
    } else if( windowWidth < 480 && windowWidth >= 359){
        this.setState({ items:2 })
    } else if( windowWidth < 360){
        this.setState({ items: 2})
    } else {
        this.setState({items:12})
    }
}

componentWillUnmount()
{
    window.removeEventListener("resize", this.updateValue);
}
Run Code Online (Sandbox Code Playgroud)

您必须将与第二个参数相同的函数传递给addEventListener / removeEventListener。当传递this.updateValue.bind(this)时,实际上是在创建一个新函数,因此这两个函数并不相同。相反,转换updateValue箭头符号,保持this作为this之类的,然后你就可以发送到同一个函数的引用两次。


god*_*nal 5

我认为你只需要在构造函数中绑定一次函数。因为 .bind() 返回一个新的函数对象,removeEventListener 不会删除您创建的初始事件侦听器函数。