javascript - 类型错误 : Cannot read property 'length' of undefined in react

标签 javascript reactjs

我正在构建一个 React 网站,它将从 newsapi 获取数据并显示在卡片上。在检查是否有一个长度之后,它将显示或显示替代响应,我收到此错误。 “类型错误:无法读取未定义的属性‘长度’”

这是我编码的内容:

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;

最佳答案

解构 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}));
}

关于javascript - 类型错误 : Cannot read property 'length' of undefined in react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57614233/

相关文章:

javascript - Canvas clearRect 仅在循环中第一次工作,发生了什么?

javascript - 为什么 deferred.resolve(object) 之后 deferred.promise 的结果和 myobject 不一样

javascript - 通过HTTP从浏览器向服务器流式传输数据的方法

CSS 帮助 - 删除图像之间的空白 (<img>)

css - 如何将颜色从 colors.jsx 导入到另一个文件

javascript - 如何有条件地在 react 组件上添加 Prop ?

javascript - 单击时动态元素 JavaScript

javascript - JQuery 不工作,可能是源错误?

javascript - 如何在onEnter函数中访问cookie,react.js

css - 在 React 中设置正文背景颜色