Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bind ES6 class methods in constructor #69

Open
klimashkin opened this issue Jan 12, 2017 · 3 comments
Open

Bind ES6 class methods in constructor #69

klimashkin opened this issue Jan 12, 2017 · 3 comments

Comments

@klimashkin
Copy link

klimashkin commented Jan 12, 2017

Seems like binding class methods in ES6 class constructor doesn't work with react-transform-hmr (which uses react-proxy)

class Test extends Component({
  constructor(props) {
    super(props);
    this.state = {open: false};
    this.handleMouseDown = this.handleMouseDown.bind(this);
    window.testInstance = this;
  }
  handleMouseDown() {
    console.log(window.testInstance === this); // false
    this.setState({open: true}); // 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  component.
  }
  render {
    return <div onMouseDown={this.handleMouseDown}>Test</div>;
  }
})

Binding in componentWillMount works:

class Test extends Component({
  constructor(props) {
    super(props);
    this.state = {open: false};
  }
  componentWillMount() {
    window.testInstance = this;
    this.handleMouseDown = this.handleMouseDown.bind(this);
  }
  handleMouseDown() {
    console.log(window.testInstance === this); // false
    this.setState({open: true}); // Ok
  }
  render {
    return <div onMouseDown={this.handleMouseDown}>Test</div>;
  }
})
@gajus
Copy link

gajus commented Apr 28, 2017

I've wasted +4 hours tracing this bug. :-(

@klimashkin
Copy link
Author

klimashkin commented Apr 28, 2017

It's still impossible to use HMR with es6 components without moving part of constructor to componentWillMount which is unwanted

@noinkling
Copy link

This is even more important now that the class properties proposal has made it to stage 3, as this is how they're transpiled.

As a reminder, in the React docs it says this:

We generally recommend binding in the constructor or using the property initializer syntax

so this is very much intended usage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants