gpt4 book ai didi

javascript - 有人知道如何修复此错误 : Can't call setState (or forceUpdate) on an unmounted component. ...?

转载 作者:行者123 更新时间:2023-11-28 17:19:57 28 4
gpt4 key购买 nike

我收到错误:无法在未安装的组件上调用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com