我正在尝试使用当前位置坐标来发出 api 请求。但是api使用的是经纬度的默认值,而不是更新后的值,从而导致请求错误。有没有办法延迟 api 请求?
RecommendContainer.jsx
function RecommendContainer() {
const [latitude, setLatitude] = React.useState(0);
const [longitude, setLongitude] = React.useState(0);
React.useEffect(() => {
navigator.geolocation.getCurrentPosition((position) => { //Retrieve current location
const lat = position.coords.latitude, lng = position.coords.longitude;
setLatitude(lat);
setLongitude(lng)
})
}, [])
return (
<div>
<HomePageNavBar />
<RecommendRestaurant latitude={latitude} longitude={longitude} />
</div>
);
}
export default RecommendContainer;
RecommendRestaurant.jsx
function RecommendRestaurant(props)
{
const url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location='
+ String(props.latitude) + ','
+ String(props.longitude)
+ '&radius=2000&type=restaurant&keyword=healthy'
+ '&key=APIkey';
const [data,setData]=React.useState([]);
var config = {
method: 'get',
dataType: 'jsonp',
url,
headers:{ }
};
const getData=()=>{
axios(config)
.then(function (response) {
console.log(response.data);
return response.data;
})
.then(function(jsonData) {
setData(jsonData);
})
.catch(function (error) {
console.log(error);
});
}
React.useEffect(()=>{
getData()
},[])
return(
<div className="recommend">
<h1 style={{fontSize: 40}}>Nearby Restaurants</h1>
<p>{props.latitude}</p>
<p>{props.longitude}</p>
</div>
)
}
export default RecommendRestaurant;
这是更新的代码.. https://codesandbox.io/s/cocky-carson-gcsxux?file=/src/App.js [更新代码]