开发者问题收集

TypeError:无法读取 React 中未定义的属性“length”

2019-08-22
313

我正在构建一个 React 网站,它将从 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个回答

您在解构 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}));
}
azundo
2019-08-22