我正在尝试在ReactJS中构建附近的餐馆应用程序,但在此命令的第一次运行中显示数组数据时遇到问题。
发生的事情是,我第一次使用axios提取数据时,它只会加载位置。第二次获取数据时,它还会在接口上呈现数组数据。
我认为问题出在我在此函数中运行的命令的顺序上,并且在第一次运行时,它尝试获取未定义的lat&lng,然后在第二次运行后,我们在同一会话中运行它,它基于什么lat&lng是使用该函数的前一次运行获取的。
这是代码:
currentLocationOnClick = async () => {
let { lat, lng } = this.state;
const URL = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${lat},${lng}&type=restaurant&radius=${5 *
1000}&key=AIzaSyBpd_v1C8RFh0D39Al97ANZ-eJLO3zrKAQ`;
navigator.geolocation.getCurrentPosition(
position => {
this.setState({ lat: position.coords.latitude });
this.setState({ lng: position.coords.longitude });
},
error => {
console.log('Error getting location');
}
);
let places;
try {
const response = await axios.get(URL);
console.log(response.data);
places = response.data.results;
} catch (error) {
console.log(error.message);
}
this.setState({ places });
};
答案 0 :(得分:0)
navigator.geolocation.getCurrentPosition
是一个异步函数,表示该函数调用在完成之前不会不阻塞。
解决此问题的一种方法是将axios调用置于position
回调中。
例如,如下所示:
async position => {
const URL = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${position.coords.latitude},${position.coords.longitude}&type=restaurant&radius=${5 *
1000}&key=AIzaSyBpd_v1C8RFh0D39Al97ANZ-eJLO3zrKAQ`;
const response = await axios.get(URL);
console.log(response.data);
places = response.data.results;
this.setState({ places });
},
另一个更好的解决方案是包装navigator.geolocation.getCurrentPosition,以便它是一个等待的函数。
类似这样的东西:
function getCurrentPosition()
{
return new Promise(resolve => navigator.geolocation.getCurrentPosition(position => resolve(position)))
}
然后您可以使用类似这样的东西:
let position = await getCurrentPosition();
const URL = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${position.coords.latitude},${position.coords.longitude}&type=restaurant&radius=${5 *
1000}&key=AIzaSyBpd_v1C8RFh0D39Al97ANZ-eJLO3zrKAQ`;
const response = await axios.get(URL);