我想检索用户在请求中使用它的位置。
但是当我想使用用户的位置进行查询时,我有一个错误,例如“未定义”不是this.state.location.coords.latitude'中的对象。
似乎位置是在政变的api请求后更新,当呼叫为空时出错的地方,但是我被阻止了我看不怎么做因为位置在componentWillMount和调用中到API是在componentDidMount。
这是我的代码,你能帮帮我吗?
async componentWillMount() {
await Font.loadAsync({
Roboto: require('native-base/Fonts/Roboto.ttf'),
Roboto_medium: require('native-base/Fonts/Roboto_medium.ttf'),
Ionicons: require('@expo/vector-icons/fonts/Ionicons.ttf'),
});
if (Platform.OS === 'android' && !Constants.isDevice) {
this.setState({
errorMessage: ' Oops, this will not work on Sketch in an Android emulator. Try it on your device !',
});
} else {
this._getLocationAsync();
}
this.setState({ loading: false });}
_getLocationAsync = async () => {
const { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== 'granted') {
this.setState({
errorMessage: 'Permission to access location was denied',
});
}
const location = await Location.getCurrentPositionAsync({});
this.setState({ location });
console.warn(this.state.location);};
componentDidMount() {
const apiURL = 'https://public.opendatasoft.com/api/';
const optionsURL = 'records/1.0/search/?dataset=evenements-publics-cibul&facet=tags&facet=placename&facet=department&facet=region&facet=city';
const dateStart = '&facet=date_start';
const dateEnd = '&facet=date_end';
const otherOptions = '&facet=pricing_info&facet=updated_at&facet=city_district&refine.date_start=2018%2F06';
const userLocation = `&geofilter.distance=${this.state.location.coords.latitude}%2C${this.state.coords.longitude}%2C30000`;
axios.get(apiURL + optionsURL + dateStart + dateEnd + otherOptions + userLocation)
.then((response) => {
this.setState({ eventList: response.data.records });
console.warn(this.state.location);
})
.catch((error) => {
console.warn(error);
});}