admin管理员组

文章数量:1299991

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

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

and this one:

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

My concern is that the second syntax isn't removing correctly the listner and it cause this warning:

Warning: setState(...): Can only update a mounted or mounting ponent. This usually means you called setState() on an unmounted ponent. This is a no-op. Please check the code for the undefined ponent.

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

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

and this one:

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

My concern is that the second syntax isn't removing correctly the listner and it cause this warning:

Warning: setState(...): Can only update a mounted or mounting ponent. This usually means you called setState() on an unmounted ponent. This is a no-op. Please check the code for the undefined ponent.
Share Improve this question edited Feb 5, 2016 at 13:29 daniele bertella asked Feb 5, 2016 at 12:10 daniele bertelladaniele bertella 7251 gold badge7 silver badges14 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

IMPORTANT:

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

According to MDN:

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

Your first approach overrides this.togglePaneHelper with new, bound function. Second one removes different event listener function than it was added - both addEventListener and removeEventListener have to get the same reference of function.

本文标签: