Reputation: 23
I got the error: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. Does anyone know how should I setState in click function to avoid this error? Thanks
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
})
}
}
Upvotes: 0
Views: 47
Reputation: 138267
Your removeEventListener
doesn't work. Two arrow functions that look the same are actually not the same:
(e => this.click(e)) === (e => this.click(e)) // false
Therefore you have to store the listener to remove it afterwards:
componentDidMount(){
this.listener = e => this.click(e);
document.addEventListener('click', this.listener);
}
componentWillUnmount() {
document.removeEventListener('click', this.listener);
}
Or you just take this.click
directly:
componentDidMount(){
document.addEventListener('click', this.click);
}
componentWillUnmount() {
document.removeEventListener('click', this.click);
}
Upvotes: 3