简体   繁体   中英

React: undefined the state of `this.setState` instantly

Why I'm getting undefined if I called console log after this.setState for the same state in componentWillMount

this example will explain the problem

    constructor(props){
        super(props);
        this.state = {
            total: 100,
            length: null,
            number: null,
        }
    }
    componentWillMount(){
        let JSONFetchedNumber = 30.20;
        this.setState({length: JSONFetchedNumber});
        console.log(this.state.length);// getting Null response


        let collect = this.state.total/this.state.length;
        let result = collect.toFixed(0)/1+1;
        this.setState({number: result});// This won't work cus length state in undefined
    }
  render() {
        console.log(this.state.length);// getting 30.20 Successfully

why I can't use the state of this.setState instantly in componentWillMount ? it works only in render

I have tried to use componentDidMount it wont works. Only in render works and my problem here that I can't use this.state in render

this.setState is an async function, it takes time to complete. If you want to log the state, the precise way is to log it in the callback of this.setState. This should work,

this.setState({length: JSONFetchedNumber}, ()=> console.log(this.state.length););

this.setState is an Async function. You are trying to access it before the state is updated. So whatever manipulations you want to do on the state, you can do it in callback function.

this.setState({length:JSONFetchedNumber},()=>{
  //Your code which is using state
  console.log(this.state)
})

You should not use length as a keyword in javascript, I'm pretty sure it's your error.

var.length is a tool in javascript to get the actual length of a variable, there must be a conflict there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM