如何在更新状态之前等待所有帖子被推送到posts数组?
我不得不迭代一堆帖子ID来获取HackerNews上的帖子,然后将所有这些ID转换成单个帖子链接,并希望将来自单个帖子链接的数据存储在一个数组中,这样我就可以迭代数组在DOM中呈现它。
import React, {Component} from 'react';
import axios from 'axios';
import Post from './Post';
class ContentWrapper extends Component {
constructor(props){
super(props);
this.state = {
posts: []
}
}
componentDidMount(){
const topStories = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty';
// `https://hacker-news.firebaseio.com/v0/item/.json?print=pretty`
axios(topStories).then(res => {
const posts = [];
res.data.map(val => {
const url = `https://hacker-news.firebaseio.com/v0/item/${val}.json?print=pretty`;
return axios.get(url).then(res => {
posts.push(res.data);
}).then(res => this.setState({posts: res}));
});
});
}
render() {
const posts = this.state.posts.map((val, i) => {
return <Post key={i} title={val.title} author={val.by} />
});
return (
<div className="content-wrapper">
<h2>{this.props.currentSource}</h2>
{posts}
</div>
)
}
}
export default ContentWrapper;
答案 0 :(得分:3)
您必须使用List<Long>
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
Promise.all