在React中使用async / await设置状态

时间:2016-07-05 09:21:36

标签: reactjs promise async-await react-native es6-promise

在代码示例中,我尝试使用setState()个对象调用Promise。必须从外部REST服务获取数据(坐标)。

在React中有这样的共同模式吗?

   async getLocations(locations) {
     var annotations = locations.map(this.getLocation);
     console.log("ANNOTATIONS:", annotations);
     this.setState({
       annotations:annotations
     });
   }

   async getLocation(location) {
      try {
        let res = await Geocoder.geocodeAddress(location.address);
        return (
          {
              latitude: res[0].position.lat,
              longitude: res[0].position.lng,
              title: location.address,
              subtitle: location.provider,
          }
        );
      }
      catch(err) {
        console.log("Error fetching geodata",err);
      }
      return null;
  }

结果数组包含Promise对象,状态更新导致错误:

ANNOTATIONS: [Promise, Promise, Promise, Promise, Promise, Promise, Promise]
ExceptionsManager.js:70 Warning: Failed prop type: Required prop `annotations[0].latitude` was not specified in `MapView`.
    in MapView (at index.js:204)
    in SampleAppInspection (at renderApplication.ios.js:90)
    in RCTView (at View.js:348)
    in View (at renderApplication.ios.js:65)
    in RCTView (at View.js:348)
    in View (at renderApplication.ios.js:64)
    in AppContainer (at renderApplication.ios.js:89)

1 个答案:

答案 0 :(得分:2)

这实际上非常简单。你需要解开你传递setState的承诺数组,因为它没有承诺意识到:

 this.setState({
   annotations: await Promise.all(annotations)
 });

Promise.all部分等待整个数组,等待为setState打开它。