TypeError:无法在React中读取未定义的属性'length'

时间:2019-08-22 17:17:53

标签: javascript reactjs

我正在建立一个反应网站,该网站将从Newsapi中获取数据并显示在卡片上。在检查之后是否会显示或显示替代响应的长度时,出现此错误。 “ TypeError:无法读取未定义的属性'length'”

这里是我的代码:

import React, { Component } from 'react';


class Cards extends Component {
 constructor () {
   super();
   this.state = {
     post: [
 {
         author:"",
         discription:"",
         publishedAt:"",
         title:"",
         urlToImage:""
       }
]
   };
 }

componentDidMount() {
fetch('https://newsapi.org/v2/top-headlines?' +
      'country=us&' +
      'apiKey=GIVEN API KEY')
    .then(response => response.json())
    .then(response => this.setState({post :response}));
}
  render() {
    const { post } = this.state;
    const postlist = post.length ? (
      post.map(post => {
        return (
          <div>
            <div class="container card mb-3">
              <div class="row no-gutters">
                <div class="col-md-4">
                  <img src={post.urlToImage} class="card-img" alt="..."/>
                </div>
                <div class="col-md-8">
                <div class="card-body">
                  <h5 class="card-title">{post.title}</h5>
                  <p class="card-text">{post.description}</p>
                    <div class="row">
                      <p class="card-text col-6"><small class="text-muted">{post.author}</small></p>
                      <p class="card-text col-6"><small class="text-muted">{post.publishedAt}</small></p>
                    </div>
                </div>
                </div>
              </div>
            </div>
          </div>
        );
      })
    )
    : (
      <div class="center">No post yet!</div>
    );


    return (
      <div class="container">
        <h2>Latest News</h2>
        {postlist}
      </div>
    );
  }
}

export default Cards;

1 个答案:

答案 0 :(得分:2)

解构this.state时出错。 const { post } = this.state.post;应该是const { post } = this.state;

编辑 从https://newsapi.org看来,响应的结构将是{status: ..., totalArticles: ..., articles: [...]}。因此,您的componentDidMount应该是:

componentDidMount() {
  fetch('https://newsapi.org/v2/top-headlines?' +
      'country=us&' +
      'apiKey=GIVEN API KEY')
    .then(response => response.json())
    .then(response => this.setState({post :response.articles}));
}