如何在React Native中在嵌套的异步for循环中设置状态?

ykejflvf  于 6个月前  发布在  React
关注(0)|答案(1)|浏览(86)

我希望这段代码片段循环通过一个数组的通用位置,包括咖啡馆的,酒吧,商店等,在每一次迭代中,我运行它通过一个谷歌的地方API,找到每一个位置与该关键字传入的是开放的,并为每一个结果,我希望它添加每个结果从API到一个状态称为placesOpen。到目前为止,它能够得到的位置没有问题,但状态没有被更新。

Geocoder.from(location).then((json) => {
        const locResult = json.results[0].geometry.location;;
        genericLocations.forEach(async (type) => {
          const response = await fetch(
            `google places url`
          );
          const data = await response.json();
          data["results"].forEach((result) => {
            setPlacesOpen(placesOpen => [result["name"],...placesOpen]);
          });
        });
      })

字符串

gdx19jrr

gdx19jrr1#

我想你可能做了很多不必要的组件更新。
为什么不这样做呢?

Geocoder.from(location).then((json) => {
        const locResult = json.results[0].geometry.location;;
        genericLocations.forEach(async (type) => {
          const response = await fetch(
            `google places url`
          );
          const data = await response.json();

          const placesToOpen = data.results
          setPlacesOpen(current => [...current, ...placesToOpen]);
        });
      })

字符串
这将只执行一个setState而不是多个。这应该可以工作,并且应该会更新您的本地状态。

相关问题