【问题标题】:React Native Asynchronous calls inside loop在循环内反应本机异步调用
【发布时间】:2017-09-16 09:54:37
【问题描述】:

我在循环中有一个以下组件,要在带有一些位置图像的某种滑块中呈现。 PlaceExtraInfo 组件是获取(http 请求)关于每个地点的一些附加信息(对于传递的 placeId),并假设将其显示在正确的地点幻灯片上:

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

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

我正在使用 Redux 并且在 PlaceExtraInfo 组件WillMount 中我正在调用 Action 来为每个 locationId 进行提取,但我被困在异步循环陷阱(关闭)中,因为在我的所有幻灯片中最终都显示了最后一个 http请求响应结果。

我知道我应该为每次迭代传递某种索引,但不知道如何在这个 fetch 迭代场景中使用它。

【问题讨论】:

    标签: javascript reactjs asynchronous react-native


    【解决方案1】:

    您可以尝试在此组件中进行提取并将其传递下来,如下所示:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-17
      • 2021-09-26
      • 2012-09-10
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 2014-11-05
      • 2019-07-31
      相关资源
      最近更新 更多