javascript - getCurrentPosition 中的 React-native-maps setState 不适用于我的 url API
问题描述
我正在研究状态的生命周期。我是 React-native 和全球 React 的新手。
我正在尝试在地图上显示来自 GooglePlacesAPI 的标记,但我的 API 的 URL无效。当我记录此 URL 时,似乎纬度和经度为“空”。
首先,我尝试在 componentDidMount() 中实现函数 getCurrentPosition,在其中设置状态“lat”和“lng”,然后是使用 URL 的 axios 函数,但我的状态为空。
所以接下来,我尝试使用回调函数。但我收到一个错误:“[未处理的承诺拒绝:TypeError:无法读取未定义的属性'setState']”
这是我的代码:
import * as React from 'react';
import { StyleSheet } from 'react-native';
import { ScrollView } from 'react-native-gesture-handler';
import MapView from 'react-native-maps';
import axios from 'axios';
var API_KEY= '###################';
var GOOGLE_PLACES_URL = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json';
class MapScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
isloading: null,
lat: null,
lng: null,
error:null,
markers: [],
};
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position);
this.setState({
lat: position.coords.latitude,
lng: position.coords.longitude,
error: null,
}, () => {
getMarkers(this.state.lat, this.state.lng)
});
},(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: false, timeout: 200000, maximumAge: 1000 },
);
// My first try was to put the axios.get(url) here.
}
function getMarkers(lat, lng){
const url =
`${GOOGLE_PLACES_URL}?location=${lat},${lng}&radius=1500&keyword=grow+shop&key=${API_KEY}`;
axios.get(url)
.then(res =>
res.data.results.map(marker => ({
latitude: `${marker.geometry.location.latitude}`,
longitude: `${marker.geometry.location.longitude}`,
name: `${marker.name}`,
isOpen: `${marker.opening_hours.open_now}`,
adress: `${marker.vicinity}`
})))
.then(markers => {
console.log(url)
console.log(markers)
this.setState({
markers,
isloading: false
})
})
.catch(error => this.setState({error, isloading: true}));
}
render() {
const { markers, lat, lng } = this.state
return (
this.state.lat !== null && <MapView style={styles.map} initialRegion={{
latitude:this.state.lat,
longitude:this.state.lng,
latitudeDelta: 1,
longitudeDelta: 1,
}}
showsUserLocation= {true}>
{markers.map(marker => {
return (<MapView.Marker
coordinate = {{
latitude:this.state.lat,
longitude:this.state.lng
}}/>)
})}
</MapView>
)}
}
export default MapScreen;
当我在 'getCurrentPosition' 中记录 'Position' 时:
Object {
"coords": Object {
"accuracy": 65,
"altitude": 11.887725830078125,
"altitudeAccuracy": 10,
"heading": -1,
"latitude": 44.83189806318307,
"longitude": -0.5747879551813496,
"speed": -1,
},
"timestamp": 1589450273414.4202,
}
该地图正在运行,因为初始区域位于我所在位置的中心。
也许我应该创建文件 'utils/getCurrentPosition' 我可以使用 React Context 来设置纬度和经度的用户?
我听说 getCurrentPosition 是“异步”的,我认为正是由于这个原因,我的第一次尝试失败了。
编辑:最后我从 APi 检索预期结果,所以我的回调函数正在工作,我只需要弄清楚如何用数据填充我的状态“标记”。当一切正常时,我会发布我的代码。
解决方案
所以现在一切正常。
回调函数非常适合此类问题。
这是我解决它的代码:
class MapScreen extends React.Component {
constructor(props) {
super(props);
this.getMarkers = this.getMarkers.bind(this);
this.state = {
isloading: true,
lat: null,
lng: null,
error:null,
markers: [],
};
}
getMarkers(lat, lng){
const url = `${GOOGLE_PLACES_URL}?location=${lat},${lng}&radius=1500&keyword=grow+shop&key=${API_KEY}`;
fetch(url)
.then(res => res.json())
.then((data) => {
this.setState({ markers: data.results });
})
.catch(error => this.setState({error, isloading: true}));
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position);
this.setState({
lat: position.coords.latitude,
lng: position.coords.longitude,
error: null }, () => {
this.getMarkers(this.state.lat, this.state.lng);
});
},(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 200, maximumAge: 1000 },
);
}
render() {
const { markers } = this.state
return (
this.state.lat !== null && <MapView style={styles.map} initialRegion={{
latitude:this.state.lat,
longitude:this.state.lng,
latitudeDelta: 1,
longitudeDelta: 1,
}}
showsUserLocation= {true}
>
{this.state.markers !== null && this.state.markers.map(marker => (
<MapView.Marker
coordinate = {{
latitude:marker.geometry.location.lat,
longitude:marker.geometry.location.lng
}}>
</MapView.Marker>
))}
</MapView>
)}
}
我没有很好地处理 JSON 的响应。
现在我愿意。我只需要将“关键道具”归因于每个道具,这很好。
推荐阅读
- python - 如何使用 rpy2 api 从 python 脚本中正确获取 R sessionInfo()?
- kotlin - Android-Things:将 gpiocallback 函数迁移到暂停协程函数
- c# - 如何在用户的声明列表中保留多个 ClaimTypes.Role 值?
- google-sheets - 查询功能按问题排序 Google 表格
- apache-beam - 如何在 Apache Beam 中生成序列号?
- c# - C# - 更改从串行端口接收的数据格式
- apache-spark-sql - 在 PySpark 中读取 DataFrames、.csv 文件时。我收到此错误“未定义名称'spark'”
- go - golang复制功能理解
- postgresql - 如何在 postgres 中为数字类型自动使用适当的精度/比例?
- ruby-on-rails - Centos 7:确保 `gem install pg -v '0.18.4' --source