Reactjs 在React中设置异步/等待状态

Reactjs 在React中设置异步/等待状态,reactjs,promise,async-await,react-native,es6-promise,Reactjs,Promise,Async Await,React Native,Es6 Promise,在代码示例中,我试图使用Promise对象数组调用setState()。数据(坐标)必须从外部REST服务获取 在React中执行此操作是否有共同的模式 async getLocations(locations) { var annotations = locations.map(this.getLocation); console.log("ANNOTATIONS:", annotations); this.setState({ annotat

在代码示例中,我试图使用
Promise
对象数组调用
setState()
。数据(坐标)必须从外部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)

这其实很简单。您需要打开正在传递的承诺数组
setState
,因为它不支持承诺:

 this.setState({
   annotations: await Promise.all(annotations)
 });
Promise.all
部分等待整个数组,而wait则将其展开,以便
setState

查看