React how to delete a list in the WillUnmount component correctly, why should I bind in the constructor?

I'm a little confused what is the difference between this sintax:

constructor(props) { super(props); this.state = { openPane: false } this.togglePaneHelper = this.togglePaneHelper.bind(this); } componentDidMount() { document.body.addEventListener('click', this.togglePaneHelper); } componentWillUnmount() { document.body.removeEventListener('click', this.togglePaneHelper); } 

and this one:

  constructor(props) { super(props); this.state = { openPane: false } } componentDidMount() { document.body.addEventListener('click', this.togglePaneHelper.bind(this)); } componentWillUnmount() { document.body.removeEventListener('click', this.togglePaneHelper); } 

My concern is that the second syntax does not correctly remove the listner and raise this warning:

 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 undefined component. 
+6
source share
1 answer

IMPORTANT:

 a.bind(this) !== a.bind(this) 

According to MDN :

The bind () method creates a new function that, when called, has this keyword set to the supplied value, with the given sequence of arguments preceding any provided when the new function is called.

Your first approach overrides this.togglePaneHelper with a new related function. Secondly, it removes another event listener function than it was added - both addEventListener and removeEventListener should get the same function reference .

+11
source

All Articles