繁体   English   中英

反应 setState 不更新 state 中的数组

[英]React setState not updating array in state

我试图简单地从这个用户中提取 API 并将数组放入 state 中的用户变量中。 然后我在 componentDidMount() 中打印它,但它打印为“未定义”。

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,
    })
  )
}

在安装组件时调用 getCaseCount() 并从中获取数据

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.

一旦收到来自 API 的响应,组件就会重新渲染,但 componentDidMount 只运行一次,因此您无法在其中看到更新的 state。

要查看更新的 state,请在渲染中写入 console.log(this.state)。

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)
}

它工作正常。 尝试将console.log放在render()中,你会看到数组有一些东西。

在您的componentDidMount中,数据需要一些时间才能获取,这就是它最初显示一个空数组的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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