我正在研究一个国家的生命周期。我是React-native和React全局的新手。
我正在尝试显示 记号笔 从GooglePlacesAPI在地图上,但我的API的URL是 无效. 当我记录这个URL时,发现经纬度是'null'。
首先,我试着在 componentDidMount()中实现函数getCurrentPosition,在那里我设置了状态 "lat "和 "lng",之后,我的axios的函数也使用了这个URL,但是我的状态是空的。
所以接下来,我尝试使用 回调函数. 但我得到一个错误:"[Unhandled promise rejection: TypeError.Cannot read property 'setState' of undefined] Cannot read property 'setState' of undefined]"
这是我的代码。
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,
}
地图是工作的,因为初始区域是在我的位置中心。
也许我应该创建文件'utilsgetCurrentPosition',在那里我可以使用React Context来设置经纬度的用户 ?
我听说getCurrentPosition是'async',我想就是因为这个原因,我的第一次尝试是失败的。
EDIT : 最后,我从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的响应。
现在我做到了。我只需要给每个prop属性'Key prop'就可以了。