我正在尝试自己的反应,并试图做一个简单的应用程序,这将显示文章从黑客新闻。我已经第一次调用了他们的API。
componentDidMount() {
fetch('https://hacker-news.firebaseio.com/v0/jobstories.json?print=pretty')
.then(res => res.json())
.then(articles => {
this.setState({articles})
})
}作为响应,它返回项目ID的数组。要获得每一篇文章的详细信息,我需要迭代我所得到的数组,并对每个项目ID进行第二个请求,该请求必须如下所示
fetch(`https://hacker-news.firebaseio.com/v0/item/{id_from_the_array}`)我面临着这个问题,因为我不知道如何正确地实现它。谁能给我个建议吗?
发布于 2018-04-24 12:22:14
这会帮你的
import React from "react";
import { render } from "react-dom";
import Hello from "./Hello";
class App extends React.Component {
state = {
articles: []
};
componentDidMount() {
fetch("https://hacker-news.firebaseio.com/v0/jobstories.json?print=pretty")
.then(res => res.json())
.then(articles => {
articles.map(item => {
fetch(`https://hacker-news.firebaseio.com/v0/item/${item}.json?print=pretty`)
.then(res => res.json())
.then(detailArticles => {
const articles = this.state.articles.concat(detailArticles);
this.setState({ articles });
});
});
});
}
render() {
return <p>{JSON.stringify(this.state.articles) }</p>;
}
}
render(<App />, document.getElementById("root"));发布于 2018-04-24 13:59:00
您可以做的一种方法是使用分页或无限滚动,这样您就可以在屏幕上显示大约10或15条新闻,并在单击按钮时加载下一组数据。否则,您只能在屏幕上显示id,并在单击按钮时获取数据。
https://stackoverflow.com/questions/50000894
复制相似问题