javascript - 在 .then 中使用 .map 时,标记组件不呈现标记
问题描述
我试图在我的地图上为一些不同的经度和纬度渲染标记,由于某种原因,当应用程序加载时,我在屏幕上看不到任何标记。我什至没有收到任何错误,调试时也看不到任何东西,这是我的渲染方法的代码。
render() {
return (
<View style={styles.container}>
{/* If user location data is allowed and retrieved */}
{this.state.ready && (
<MapView
provider={PROVIDER_GOOGLE}
showsUserLocation
style={styles.map}
region={{
latitude: this.state.coords.lat,
longitude: this.state.coords.lng,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421
}}
>
{this.renderVendorMarkers()}
</MapView>
)}
</View>
);
}
}
这个状态。ready 是指我根据某些权限设置的布尔属性。
渲染标记的方法是“this.renderVendorMarkers()”,该方法的代码如下:
renderVendorMarkers = () => {
const { locations } = this.state;
this.getCoordinates(locations).then(coords => {
return (
<View>
{coords.map((coord, idx) => {
return (
<Marker
key={idx}
coordinate={{ latitude: coord.lat, longitude: coord.lng }}
/>
);
})}
</View>
);
});
};
此方法引用了一个位置属性,该属性链接到一个带有用户完整地址的 json 文件和另一个名为 getCoordinates 的方法,该方法返回与 google.maps api 对应的一组 promise 以获取地址。
getCoordinates = vendors => {
const APIKEY = "myApiKey"; //Put a fake value here but in code, use a real API key
const promises = vendors.map(async vendor => {
const vendorID = vendor.VendorID;
const fullAddress = `${vendor.VendorAddress},${vendor.VendorCity},${vendor.VendorState}`;
try {
const resp = await fetch(
`https://maps.googleapis.com/maps/api/geocode/json?address=${fullAddress}&key=${APIKEY}`
);
const respJson = await resp.json();
return respJson.results[0].geometry.location;
} catch (err) {
console.log(err);
}
});
return Promise.all(promises);
};
基本上,我有一个包含用户地址列表的 json 文件。我想用用户的经度和纬度在地图上放置标记。
我的 getCoordinates 方法按我想要的方式工作。似乎问题出在 renderVendorMarkers 方法上。循环遍历坐标列表(从 getCoordinates 方法检索)时,标记不会呈现。如果您希望我进一步澄清,请告诉我。感谢帮助。
解决方案
只是为了关闭它,答案如下:
- 在
componentDidMount()
. 这里我设置了状态。
this.getCoordinates(this.state.locations).then(coords => {
this.setState({ vendorCoords: coords });
});
- 在组件的 render 方法中,我调用
renderVendorMarkers()
.
{this.renderVendorMarkers()}
renderVendorMarker 方法本身是:
renderVendorMarkers = () => {
const { vendorCoords } = this.state;
if (vendorCoords) {
return (
<View>
{vendorCoords.map((vendorCoord, idx) => {
return (
<Marker
key={idx}
coordinate={{
latitude: vendorCoord.lat,
longitude: vendorCoord.lng
}}
/>
);
})}
</View>
);
}
};
推荐阅读
- sonarqube - Sonarqube 数据迁移
- java - 用 \n 替换换行符,用 \t 替换制表符
- python - 在循环中连续调用函数并打印不同的结果
- http - 不完全 HTTPS webapp 上的服务工作者
- mql5 - 无法通过指标 MQL5 返回值
- java - 将接口和对象中的设置器放入数组
- javascript - 根据angularjs中的键和最新的时间戳键过滤json
- r - 使用 purrr::walk 设置多个事件观察者
- wordpress - 由 dFactory cookie 插件创建的 Wordpress 页脚中的代码
- push-notification - RingCentral 的来电通知