【问题标题】:Setting state with async/await in React在 React 中使用 async/await 设置状态
【发布时间】:2016-11-07 01:38:04
【问题描述】:

在代码示例中,我尝试使用 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)

【问题讨论】:

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


【解决方案1】:

这其实很简单。你需要解开你传递的承诺数组setState,因为它不知道承诺:

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

Promise.all 部分等待整个数组,await 为setState 解包。

【讨论】:

    猜你喜欢
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 2015-09-29
    • 1970-01-01
    • 2019-09-09
    • 2019-04-24
    • 2023-03-31
    相关资源
    最近更新 更多