我收到错误:无法在未安装的组件上调用 setState(或forceUpdate)。这是一个空操作,但它表明应用程序中存在内存泄漏。有谁知道我应该如何在 click 函数中 setState 以避免此错误?谢谢
class List extends Component {
constructor(props) {
super(props);
this.state = {
showMenu: null
};
}
showMenu = (id) => {
this.setState(prevState => ({
showMenu: prevState.showMenu===null ? id : null,
}))
}
componentDidMount(){
document.addEventListener('click', (e)=>this.click(e))
}
componentWillUnmount() {
document.removeEventListener('click', (e)=>this.click(e))
}
click = (e) => {
if(e.target.className!=='flaticon-menu white'){
this.setState({
showMenu:null
})
}
}
最佳答案
您的removeEventListener
不起作用。两个看似相同的箭头函数实际上并不相同:
(e => this.click(e)) === (e => this.click(e)) // false
因此,您必须存储监听器以便随后将其删除:
componentDidMount(){
this.listener = e => this.click(e);
document.addEventListener('click', this.listener);
}
componentWillUnmount() {
document.removeEventListener('click', this.listener);
}
或者你直接使用this.click
:
componentDidMount(){
document.addEventListener('click', this.click);
}
componentWillUnmount() {
document.removeEventListener('click', this.click);
}
关于javascript - 有人知道如何修复此错误 : Can't call setState (or forceUpdate) on an unmounted component. ...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52677063/