[英]TypeError: Cannot read property 'length' of undefined in react
我正在建立一个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;
销毁this.state
时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}));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.