简体   繁体   中英

React setState not updating array in state

I am trying to simply pull from this users API and put the array into the users variable in state. I am then printing it in componentDidMount(), but it prints as 'undefined'.

state = {
      users: [],
    }


  componentDidMount() {
    this.getCaseCount();
    console.log(this.state.users);
  }

//CoronaVirus API Goes here
getCaseCount(){
  fetch(`https://jsonplaceholder.typicode.com/users`)
  .then(response => response.json())
  .then(data =>
    this.setState({
      users: data,
    })
  )
}

On mounting of your component getCaseCount() is called and its fetching the data from

https://jsonplaceholder.typicode.com/users

while waiting for the response from API it moves on to the next part and logs the state but at this time the state is not updated as data has not been received, so it shows initial value of state which is an empty array.

Once the response from API is received the component is rerendered but componentDidMount runs only once hence you cannot see the updated state in it.

To see updated state write console.log(this.state) in render.

state = {
      users: [],
    }


  componentDidMount() {
    this.getCaseCount();
    console.log(this.state.users);
  }

//CoronaVirus API Goes here
getCaseCount(){
  fetch(`https://jsonplaceholder.typicode.com/users`)
  .then(response => response.json())
  .then(data =>
    this.setState({
      users: data,
    })
  )
}

render{
   console.log(this.state.users)
}

It works fine. Try to put console.log inside render() , you'll see the array has something.

In your componentDidMount the data takes some time to get fetched which is why it shows an empty array initially.

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