为由newsapi驱动的新闻应用程序构建一个发布区域,该区域应显示具有“ url”匹配而不是“ id”匹配的属性的特定文章。现在,我希望它显示文章内容,如果有的话,否则它应该显示一条错误消息,在这种情况下为“错误加载文章”。它仅显示错误加载文章。
这就是我所做的:
import React, { Component } from 'react';
class Post extends Component {
constructor () {
super();
this.state = {
post: [
{
url:"",
content:"",
author:"",
publishedAt:"",
title:"",
urlToImage:""
}
]
};
}
componentDidMount() {
let url = this.props.match.params.post_url;
fetch('https://newsapi.org/v2/top-headlines?' +
'country=us&' +
'apiKey=fe76e3e41c7647358505016dad4f958a' + url )
.then(response => response.json())
.then(response => this.setState({post :response.articles}));
}
render() {
const { post } = this.state;
const postcard = post ? (
<div class="card card-cascade wider reverse">
<div class="view view-cascade overlay">
<img class="card-img-top" src={post.urlToImage} alt="Card image cap"/>
<a href="#!">
<div class="mask rgba-white-slight"></div>
</a>
</div>
<div class="card-body card-body-cascade text-center">
<h4 class="card-title"><strong>{post.title}</strong></h4>
<h6 class="font-weight-bold indigo-text py-2">{post.author}</h6>
<p class="card-text">{post.content}</p>
<p><a class="px-2 fa-lg li-ic">Source:{post.source}</a></p>
</div>
</div>
)
: (
<div class="center">Error loading article.</div>
);
return (
<div class="container">
<h2></h2>
{postcard}
</div>
);
}
}
export default Post;
谢谢。
答案 0 :(得分:0)
您正在引用传递到该组件中的道具
let url = this.props.match.params.post_url;
但是
class Post extends Component {
constructor () { // no props
super(); // no props
this.state = {
post: [
{
url:"",
content:"",
author:"",
publishedAt:"",
title:"",
urlToImage:""
}
]
};
}
您没有传递从上级组件收到的道具。因此,this.props.match.params.post_url
将始终为undefined
,并将undefined
连接到字符串实际上是在字符串的末尾附加字符串“ undefined”。因此,您的网址格式不正确,并且设置为this.state.post
的响应将与您期望的JSON模式不匹配。可能是来自API的错误响应。