【发布时间】:2020-07-26 11:50:17
【问题描述】:
我正在尝试构建一个用于个人目的的新闻阅读器(并练习我所学的内容),但我的文章列表有问题,我从 NewsApi 和 Reddit 头版获取。我没有 API,因为我认为创建一个只是为了获取文章是没有用的,而且我没有存储它们,所以它都在我的 React 应用程序中。
代码如下:
componentDidMount() {
let posts = [];
fetch(`https://www.reddit.com/r/all.json`)
.then(resp => resp.json())
.then(redditAllPosts => {
redditAllPosts.data.children.map((redditSinglePost) => {
const { author, title, subreddit, permalink, created_utc } = redditSinglePost.data;
let redditPost = {
'sourcePost': 'Reddit',
'date': created_utc,
'title': title,
'author': author,
'url': `https://www.reddit.com${permalink}`,
'subredditUrl': `https://www.reddit.com/r/${subreddit}`,
};
posts.push(redditPost);
})
})
fetch(`https://newsapi.org/v2/top-headlines?country=us&apiKey=${process.env.REACT_APP_API_KEY}`)
.then(resp => resp.json())
.then(newsApiPosts => {
newsApiPosts.articles.map((newsApiSinglePost) => {
const dateNewsApiPost = moment(newsApiSinglePost.publishedAt).unix();
const { author, title, url } = newsApiSinglePost;
let newsApiPost = {
'sourcePost': 'NewsApi',
'date': dateNewsApiPost,
'title': title,
'author': author,
'url': url,
'sourceNews': newsApiSinglePost.source.name
};
posts.push(newsApiPost);
})
return posts;
})
.then(posts => {
this.setState({posts})
})
}
constructor() {
super()
this.state = {
posts: null,
filtersTheme: null, ( will be implemented later )
filtersCountry: null ( will be implemented later )
}
}
因此,基本上,一旦安装了应用程序,它就会从 Reddit 获取帖子,映射获取的内容并将按我的方式格式化的文章推送到帖子数组,它对 NewsAPI 帖子也是如此。完成此操作后,程序将设置状态,我尝试在每一步中记录几乎所有内容。它记录了包含 20 个 NewsAPI 帖子和 45 个 Reddit 帖子的完整数组,但它只显示数组的前 20 个帖子。日志的包裹线是这样的:
(20) [{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…} , {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
那是从哪里来的?
【问题讨论】:
标签: javascript arrays reactjs components state