【发布时间】:2019-10-06 05:03:28
【问题描述】:
这是我的 json 网址:
http://ec2-13-233-199-251.ap-south-1.compute.amazonaws.com/api/keyword/modi
{
"Republic": [
{
"headline": "Now, Robert Vadra scoffs at PM Modi's Kedarnath visit, exclaims 'Wow !! What’s going on ...'",
"link": "https://www.republicworld.com/india-news/general-news/now-robert-vadra-scoffs-at-pm-modis-kedarnath-visit-exclaims-wow-whats-going-on-dot",
"date": "2019-05-19 20:51:07.261913",
"category": null,
"sentiment": null
}
],
"Ndtv": [
{
"headline": "Blog: Is Modi Moving Mamata Banerjee's Cheese In Bengal?",
"link": "https://www.ndtv.com/blog/is-modi-moving-mamata-banerjees-cheese-in-bengal-2039156?pfrom=home-opinion",
"date": "2019-05-19 20:51:50.218228",
"category": null,
"sentiment": null
}
],
"Indiatv": [
{
"headline": "Modi's Kedarnath Yatra is being widely covered by media, this is gross violation of MCC: TMC to Election Commission",
"link": "https://www.indiatvnews.com/news/india-election-2019-modi-kedarnath-yatra-is-being-widely-covered-by-media-this-is-gross-violation-of-mcc-tmc-to-election-commission-520982",
"date": "2019-05-19 20:50:48.145723",
"category": null,
"sentiment": null
}
],
"Thehindu": [
{
"headline": "Early life stress can modify DNA expression, a study finds",
"link": "https://www.thehindu.com/sci-tech/science/early-life-stress-can-modify-dna-expression-a-study-finds/article27172334.ece",
"date": "2019-05-19 20:50:51.485027",
"category": null,
"sentiment": null
}
],
"Zeenews": [
{
"headline": "Lok Sabha election 2019: PM Modi offers prayers at Badrinath temple\n",
"link": "https://zeenews.india.com/video/india/lok-sabha-election-2019-pm-modi-offers-prayers-at-badrinath-temple-2204365.html",
"date": "2019-05-19 20:50:55.60367",
"category": null,
"sentiment": null
}
],
}
我编写了以下代码来在我的反应组件中显示新闻 Source Republic、Ndtv、Zenews 的标题链接日期:
class keywordNews extends Component {
state = {
data:[]
}
componentDidMount(){
const keyword=localStorage.getItem('keyword');
const url=`http://ec2-13-233-199-251.ap-south-1.compute.amazonaws.com/api/keyword/${keyword}`;
console.log(url);
axios.get(url)
.then(res => {
this.setState({data:res.data.Republic
});
console.log(res.data);
});
}
render() {
return (
<div>
<h1>{localStorage.getItem('keyword')}</h1>
<Show data={this.state.data} />
</div>
)
}
}
显示组件:
class Show extends Component {
render() {
return (
<div>
<div>
{this.props.data.map(({headline,link,date }, index) =>
<div key={index}>
<div>
<h3><a href={link}>{headline}</a></h3>
<h6>{date}</h6>
</div>
</div>
)}
</div>
<br></br>
</div>
)
}
}
export default Show;
从上面的代码中,我得到了只有共和国数组的标题链接。但我想为数组中的所有索引编写代码,例如 Ndtv、Indiatv、The Hindu。
我是前端开发的新手。请帮助我如何显示来自 API 的所有数据。
【问题讨论】:
-
In componentDidMount 你只为共和国取数据 this.setState({data:res.data.Republic});
-
是的,我应该为所有其他人做什么?
-
@imsaiful 不是分配republic,而是将整个数据获取到组件状态,然后迭代数据。所以它会像 this.state.data.republic.map()
-
好的,我会这样做,但我应该怎么做,比如 Zeenews,ndtv 等。如果你只为组件写这个答案会更好。谢谢。
标签: javascript json reactjs api