我写了这段代码
componentDidMount(){
Geolocation.getCurrentPosition(info => {
console.log(info.coords.latitude + " " + info.coords.longitude)
this.setState({coords: {latitude: info.coords.latitude, longitude: info.coords.longitude, latitudeDelta: this.LATITUDE_DELTA, longitudeDelta: this.LONGITUDE_DELTA}})
}, error => Alert.alert('Error', JSON.stringify(error)),
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000});
console.log(this.state.coords.latitude + " " + this.state.coords.longitude);
region = getapi(this.state.coords.latitude, this.state.coords.longitude)
this.setState({region})
console.log("TEMP: " + region);
hot = getHotBarb(this.state.region)
this.setState({hot})
rated = getRatedBarb(this.state.region)
this.setState({rated})
offer = getOfferBarb(this.state.region)
this.setState({offer})
this.setState({loading: false})
}
但是在日志控制台上,我首先看到this.state.coords.latitude +“” + this.state.coords.longitude(未定义)的日志以及getCurrentPosition调用内的日志(正确)。
问题是我无法调用函数getapi,因为this.state.coords.latitude,this.state.coords.longitude结果未定义
我需要先设置this.state.coords.latitude
和this.state.coords.longitude
,然后在componentDidMount()
中调用其他函数。
如何在其他函数之前调用getCurrentPosition函数上的setState?
答案 0 :(得分:-1)
尝试这种方式
callApi(){
console.log(this.state.coords.latitude + " " + this.state.coords.longitude);
region = getapi(this.state.coords.latitude, this.state.coords.longitude)
this.setState({region})
console.log("TEMP: " + region);
hot = getHotBarb(this.state.region)
this.setState({hot})
rated = getRatedBarb(this.state.region)
this.setState({rated})
offer = getOfferBarb(this.state.region)
this.setState({offer})
this.setState({loading: false})
}
getCurrentPosition(){
Geolocation.getCurrentPosition(info => {
console.log(info.coords.latitude + " " + info.coords.longitude);
this.setState({coords: {latitude: info.coords.latitude, longitude: info.coords.longitude, latitudeDelta: this.LATITUDE_DELTA, longitudeDelta: this.LONGITUDE_DELTA}},
() => this.callApi(); // call api here
)
}, error => Alert.alert('Error', JSON.stringify(error)),
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000});
}
componentDidMount(){
this.getCurrentPosition();
}