首页 > 解决方案 > TypeError:无法读取未定义的属性(读取“地图”)

问题描述

      constructor() {
        super();
        console.log("Hii this is a constructor");
        this.State = {
         articles: [],
      loading: false
    };
  }
  async componentDidMount() {
    let url =
      "https://newsapi.org/v2/top-headlines?country=in&apiKey=c7908fc25bbc49589fcaedcedfb2e114";
      
    let data = await fetch(url);
    let parsedata = await data.json()
    console.log(parsedata)
    this.setState({articles: parsedata.articles});
  }
  render() {
    return (
      <div className="container ">
        <h3 className="my-3">Top Headlines </h3>
        <div className="row">
          {this.articles.map((element) => {
            return (
              <div className="col-md-4" key={element.url}>
                <Nitems
                  title={element.title.slice(0, 50)}
                  description={element.description}
                  img={element.urlToImage}
                  nurl={element.url}
                ></Nitems>
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}

export default News;

标签: reactjs

解决方案


它应该是这样的:

this.state = {  //<-- With non capitalize letter
     articles: [],
  loading: false
};

和这个:

this.state.articles.map((element) => //<-- With "state"

apiKey也请隐藏你的


推荐阅读