Home > Mobile >  Why this is not accessible in static methods such as static getDerivedStateFromProps(props,state) in
Why this is not accessible in static methods such as static getDerivedStateFromProps(props,state) in

Time:10-19

I am a beginner in react and while learning lifecycle methods I came to know getDerivedStateFromProps() is a method of mounting lifecycle but while going further I came to understand that this is not accessible to static methods can anyone please explain why it is like this?

CodePudding user response:

This is a core fundamental of Object Oriented Programming. In React, every component when run creates an instance of a class. In object oriented programming, static properties exist on the whole class and not on the instance. (An instance of a class is called an object). this refers to the component instance, so every instance of the component will have a different this. Since in this case, there is no instance, there is no this.

CodePudding user response:

This is not specific to React, but to JavaScript itself.

The static keyword defines static methods or properties. The behavior you see is because neither static methods nor static properties can be called on instances of the class (and the this refers to the current instance of the class). Instead, static methods/properties are called on the class itself.

A demo may make it clearer:

class MyClass {
  instanceProperty = 'instancePropertyValue';
  instanceMethod() {
    console.log('here, the `this` is accessible, as well as instance properties:');
    console.log(this.instanceProperty);
  }
  static staticProperty = 'staticPropertyValue';
  static staticMethod() {
    console.log('here, the `this` is NOT accessible, only static methods/properties:');
    console.log(MyClass.staticProperty);
  }
}

MyClass.staticMethod(); // works
// MyClass.instanceMethod(); // doesn't work

const myInstance = new MyClass();
myInstance.instanceMethod(); // works
// myInstance.staticMethod(); // doesn't work

Notice there's no React-specific code above.

  • Related