简体   繁体   English

setState()在反应js中基于class的组件中不起作用

[英]setState() not working in class based component in react js

  constructor(){
    super();
    this.state = {
      articles: this.articles,
      loading: false
    }
  }

  //always run after the render method
  async componentDidMount(){
    let url = "https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=7d5e22019e7e4b519b0a7776738ac065";
    let data = await fetch(url);
    let parseData = await data.json();
    let updateArticle = parseData.articles;
    this.setState({
        articles: updateArticle
    });    // console.log(this.articles)
  }

I was expected to replace the articles with updateArticle using setState() But it is not working but i got the correct value in the updateArticle but cant asssign to articles我应该使用 setState() 将文章替换为 updateArticle 但它不起作用但我在 updateArticle 中得到了正确的值但无法分配给文章

super() should include props of the component. super()应该包含组件的 props。 this scope would not work otherwise.否则, this scope 将无法工作。 check this related article .检查这篇相关文章

// incorrect way
constructor() {
  super();
  // ...
}

// correct way
constructor(props) {
  super(props);
  // ...
}

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

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