繁体   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