在React中设置async/await的状态
问题描述:
在代码示例中,我试图用Promise
对象的数组调用setState()
。数据(坐标)必须从外部REST服务中获取。在React中设置async/await的状态
在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;
}
结果数组包含无极对象和状态更新会导致错误:
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
部分等待和的await解开它setState
。
看看https://stackoverflow.com/questions/37576685/using-async-await-with-foreach-loop – Bergi