I'm new to reactjs and tried to make a component. I set this.state in componentWillMount() and after that I call a method:
componentWillMount() {
this.setState({ value: this.props.value || "0" });
this.changeCbState = this.changeCbState.bind(this);
this.changeCbState();
}
But in my method changeCBState this.state is undefined:
changeCbState() {
console.log(this.state.value)
}
Error: Uncaught TypeError: Cannot read property 'value' of null
The problem could be that you wouldn't have initialised state in the constructor and since this.setState is asynchronous the state may not be initialsed before you are trying to access in changeCbState function.
Also the initialisation code that you have written in componentWillMount lifecycle needs to go in constructor since the componentWillMount method is supposed to be deprecated.
constructor(props) {
super(props);
this.state = {
value: this.props.value || "0"
}
this.changeCbState = this.changeCbState.bind(this);
this.changeCbState();
}
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