我正在尝试出于个人目的(并实践我所学的知识)构建新闻阅读器,而我在从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中获取帖子,在获取的内容上进行映射,并将以我的方式格式化的文章推送到posts数组,并且对NewsAPI帖子也是如此。完成此操作后,该程序将设置我尝试控制台日志的状态,几乎每一步都完成。它记录了包含20个NewsAPI帖子和45个Reddit帖子的完整数组,但仅显示该数组的前20个帖子。日志的总结行是这样的:
(20)[{...},{...},{...},{...},{...},{...},{...},{...},{...},{...},{...}, {…},{…},{…},{…},{…},{…},{…},{…},{…}]
那从哪里来?
改用它:
this.setState(prevState => ({ posts: [...prevState.posts, ...posts] })
这样,您只添加到状态中的帖子,而不会覆盖它们。