2017-04-20 119 views
0

我在循環中有一個下面的組件,在一些帶有一些地方圖像的滑塊中被渲染。該PlaceExtraInfo組件是取(http請求)對每個地方的一些附加信息(用於傳遞placeId),並假設來顯示它在適當的位置幻燈片:React Native在循環內異步調用

return places.map((place, index) => 

    // there will be a fetch for each place id in the component 
    <PlaceExtraInfo placeId={place.id} key={index} /> 
); 

我使用的終極版,並在PlaceExtraInfo componentWillMount我正在調用Action來爲每個locationId執行提取操作,但是我陷入了異步循環陷阱(閉包),因爲我的所有幻燈片都顯示最後的http請求響應結果。

我知道我想爲每次迭代傳遞某種索引,但不知道如何在這個獲取迭代場景中使用它。

回答

0

你可以嘗試做這個組件中取出來,並將它傳遞下去,是這樣的:

const placesInfo = await Promise.all(places.map(place => 
    fetch(url) //pass whatever you need from place into fetch 
    .then((response) => <PlaceExtraInfo placeInfo={response} key={place.id} />) 
)) 
//so now you will be making the api call and passing the info down to your component 
//and this will return an array of all the components