卸载组件后,调整窗口大小时出现错误。我知道 window.removeEventListener
正在被调用,但它的行为就好像它从未被调用一样。错误提示:
warning.js:36 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 HeaderMain component.
我什至尝试使用 React 文档中的代码示例,它的作用与我的类所做的相同。来自 https://facebook.github.io/react/tips/dom-event-listeners.html :
import React from "react";
var HeaderMain = React.createClass({
getInitialState: function() {
return {windowWidth: window.innerWidth};
},
handleResize: function(e) {
this.setState({windowWidth: window.innerWidth});
},
componentDidMount: function() {
window.addEventListener('resize', this.handleResize);
},
componentWillUnmount: function() {
window.removeEventListener('resize', this.handleResize);
},
render: function() {
return <div>Current window width: {this.state.windowWidth}</div>;
}
});
module.exports = HeaderMain;
我尝试过使用 bind()
,在 ES6
中尝试过,并尝试过不同版本的 React.js
>。我无法消除该错误。
如何确保我的事件监听器将被删除?
最佳答案
我发现这与绑定(bind)有关。当您调用 .bind(this) 时,它会返回一个具有所需范围的新函数,因此它不会取消注册我认为添加的相同函数。
此外,我发现无论出于何种原因,在 ES6 + React v15.3.1(最新)中,自动绑定(bind)不会像 ES5(React 的同一版本)中那样发生(我认为应该发生),所以我只是存储了对绑定(bind)函数的引用,并重用了它。
import React from "react";
export default class HeaderMain extends React.Component {
boundFunc = this.handleResize.bind(this);
constructor()
{
super();
this.state = {height:window.innerHeight + "px"};
}
handleResize(e)
{
this.setState({height:window.innerHeight + "px"});
}
componentDidMount()
{
window.addEventListener('resize', this.boundFunc);
}
componentWillUnmount()
{
window.removeEventListener('resize', this.boundFunc);
}
render() {
return (
<header class="header_main" style={{height:this.state.height}}>
Example Header
</header>
);
}
}
关于javascript - 在 React.js 中,使用 componentWillUnmount 删除事件监听器,如何确保事件监听器被删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39398993/