Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs component `this.state` undefined

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


1 Answers

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();
    }
like image 188
Shubham Khatri Avatar answered Feb 25 '26 20:02

Shubham Khatri