2017-12-06 15 views
0

状態を更新する前にすべての投稿が投稿配列にプッシュされるのを待つ方法はありますか?コードの次の行に進む前に.map()の実行が完了するまで待つ方法

私は、HackerNewsのトップ記事を取得するために投稿IDの配列を繰り返し処理しなければなりませんでした。これらのIDをすべて単一の投稿リンクに変換し、1つの投稿リンクのデータを配列に格納して、その配列を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

を非同期を使用してください。 https://medium.com/front-end-hacking/async-await-with-react-lifecycle-methods-802e7760d802 –

+1

'Promise.all' - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise /すべて – TryingToImprove

答えて

1

あなたはPromise.all使用する必要があります - ここhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

const topStories = 
    "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty"; 

axios(topStories).then(res => { 
    const posts = []; 

    const requests = 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); 
    }); 
    }); 

    // Wait for all requests, and then setState 
    Promise.all(requests).then(() => { 
    this.setState({ 
     posts 
    }); 
    }); 
}); 

テストを:私はaxiosを使用しませんが、あなたは試してみてくださいhttps://runkit.com/embed/8pac53dhmy2y

+0

私は血まみれにPromise.allとは何かがあることを知っていましたが、どこに置くのかは分かりませんでした。 –

+0

正しい@ B.Maugerの場合は答えとして追加してください:) – TryingToImprove

関連する問題