簡體   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