簡體   English   中英

React無法設置狀態

[英]React can't set state

我正在使用React並嘗試使用API​​中的數據填充ImageGrid。 獲取數據沒有問題,但不知何故我無法使用responseData設置我的狀態

我從API獲得響應時可以顯示數據,但我無法設置狀態...

componentWillMount()
{
  this.state = {
    content: ''
  };

   this.loadContent();
}

loadContent()
{
  ApiService.getTweets(topic,numberOfElements,offset).then((responseData) => {
    console.log("Data is here",responseData); //<---------- HERE
    this.setState({
      content: responseData
    });
  })
  console.log("Data is not here",this.state.content); //<---------- HERE
}

我在這里得到數據:

class ApiService {    

  static getTweets() {      

    return fetch("https://MyURL", {
            method: 'get'
          })
          .then((resp) => resp.json())
          .then(function(data) {

            return data;
          }).catch(function(error) {
            console.log(error);// Error :(
          });
    }
  }
export default ApiService;

您有異步問題: fetchsetState都是異步的。

loadContent() {
  ApiService.getTweets(topic,numberOfElements,offset).then((responseData) => {
    console.log("Data is here",responseData); //<---------- HERE
    this.setState({
      content: responseData
    }, () => {
       // only now the state was updated
       console.log("Data is here", this.state.content); 
    });

    // even the nest line runs to early
    console.log("Data is not here",this.state.content); 

  })
  // the next line runs to early
  console.log("Data is not here",this.state.content);
}

您希望使用set狀態回調,因為狀態未立即設置。

loadContent() {
  ApiService.getTweets(topic,numberOfElements,offset).then((responseData) => {
    console.log("Data is here",responseData); //<---------- HERE
    this.setState({
      content: responseData
    }, () => {
      console.log("Data is here",this.state.content); //<---------- HERE
    );
  })
}

您需要實現componentDidUpdate 不要依賴承諾來了解組件何時更新。 React的生命周期將在系統更新擔心。 見下文。

從那時起,您可以輕松地做類似的事情

componentDidUpdate(prevProps, prevState) {
  if(prevState.content !== this.state.content) {
    console.log('I have new content!', this.state.content);
  }
}

此外,如果組件中只有一個setState()調用,則可以忽略該if語句。 所以簡短版本如下:

componentDidUpdate(prevProps, prevState) {
  console.log('I have new content!', this.state.content);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM