#javascript #reactjs #react-native
#javascript #reactjs #react-native
Вопрос:
я написал этот фрагмент кода
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()
.
Как я могу получить setState для функции getCurrentPosition, которая будет вызываться перед другими функциями?
Ответ №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();
}