Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React getDerivedStateFromProps not able to access this

I am using getDerivedStateFromProps lifecycle hook in latest react 16.5.2. Why I am not able to access the this object for component? Is there anything I am doing wrong.

class EmailInput extends Component {
  state = { email: this.props.defaultEmail };

  handleChange = event => {
    this.setState({ email: event.target.value });
  };

  getDerivedStateFromProps() {
    this.doSomething();
  }

  doSomething = () => {
   //do something here
  }

  render() {
    return <input onChange={this.handleChange} value={this.state.email} />;
  }
}
like image 934
Sagar Kharche Avatar asked Oct 03 '18 15:10

Sagar Kharche


1 Answers

You cannot use this to access non-static method. You need to define static method:

static getDerivedStateFromProps() {
    EmailInput.doSomething();
   // ^^ class name
   //OR,
   // this.doSomething(); // accessible, coz doSomething is now static method
}
static doSomething() {
   //do something here
}

You can learn more about static method here in mdn docs.


Furthermore, we use this.props, this.state to access props and states respectively in non-static method. But since getDerivedStateFromProps is a static method, we need to access from it's params:

static getDerivedStateFromProps(props, state) {
  // correct
  console.log(props, state)
 // incorrect
 // console.log(this.props, this.state)
 // `this` can be used only for static methods
 // that are inside the class
}
like image 73
Bhojendra Rauniyar Avatar answered Nov 03 '22 07:11

Bhojendra Rauniyar