简体   繁体   English

React无法设置状态

[英]React can't set state

I'm working in React and trying to fill a ImageGrid with data from a API. 我正在使用React并尝试使用API​​中的数据填充ImageGrid。 There is no problem with getting the data but somehow I cant set my state with the responseData 获取数据没有问题,但不知何故我无法使用responseData设置我的状态

I can show the data while I get the response from the API but I can't set my state... 我从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
}

Here I get the data: 我在这里得到数据:

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;

You have async issue: both fetch and setState are async. 您有异步问题: 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);
}

You want to use the set state callback as state is not set instantly. 您希望使用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
    );
  })
}

You need to implement componentDidUpdate . 您需要实现componentDidUpdate Don't rely on the promises to know when your component has updated. 不要依赖承诺来了解组件何时更新。 React's life-cycle will worry about that after the system has updated. React的生命周期将在系统更新担心。 See below. 见下文。

From that point you can easily do something like 从那时起,您可以轻松地做类似的事情

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

Also, you can ignore that if statement if you only have one setState() call in your component. 此外,如果组件中只有一个setState()调用,则可以忽略该if语句。 So the short version is as follows: 所以简短版本如下:

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