score:3

Accepted answer

When those class properties are transpiled, they get moved to the end of the constructor, in the order that they are written. So when you do this...

class Example {
  state = {
    hello: this.hello()
  }; 

  hello = () => {
    return 'hello;
  };
}

...it gets transpiled into roughly this:

class Example {
  constructor() {
    this.state = {
      hello: this.hello()
    };

    this.hello = () => {
      return 'hello;
    };
  }
}

In this transpiled code, you're trying to access this.hello before this.hello has been defined, and thus you get the error. Instead, you need to change the order, so that you define the function first, and use it after.

class Example {
  hello = () => {
    return 'hello;
  };

  state = {
    hello: this.hello()
  }; 
}

Related Query

More Query from same tag