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} />;
}
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With