我确信这与定时、地理位置和获取数据的axios有关。使用useEffect,它会给予错误的位置。如果我不使用useEffect调用函数,我会得到正确的位置,但这会产生一个无限循环。我也尝试过在useEffect中使用条件。并尝试过使用setTimeout;
如何确保navigator.geolocation在获取数据之前具有lat和long?
import React from 'react';
import { useState, useEffect } from 'react';
import './css/weather.css'
import axios from 'axios';
const Weather = () => {
const [lat, setLat] = useState(0);
const [long, setLong] = useState(0);
const [temp, setTemp] = useState(0);
const [wind, setWind] = useState('');
const [windDir, setWindDir] = useState('');
const [gust, setGust] = useState('');
const [precip, setPrecip] = useState(0);
const [icon, setIcon] = useState('');
const [pic, setPic] = useState('');
const [city, setCity] = useState('');
const getWeather = async () => {
try {
await navigator.geolocation.getCurrentPosition((position) => {
setLat(position.coords.latitude);
setLong(position.coords.longitude);
})
const response = await axios.get(`http://api.weatherapi.com/v1/current.json?key=6e6263afb84f44279f731543222510&q=${lat},${long}&aqi=no`);
console.log(response.data)
setCity(response.data.location.name)
setTemp(response.data.current.temp_f);
setWind(response.data.current.wind_mph);
setWindDir(response.data.current.wind_dir);
setGust(response.data.current.gust_mph);
setPrecip(response.data.current.precip_in);
setPic(response.data.current.condition.icon.slice(-7))
if(response.data.current.condition.icon.includes('day')){
setIcon(<img src={`/assets/weather/64x64/day/${pic}`}></img>
)
} else {
setIcon(<img src={`/assets/weather/64x64/night/${pic}`}></img> )
}
} catch (err) {
console.error(err)
}
}
useEffect(() =>{
getWeather();
},[])
return (
<div className='weather-container'>
<p>{icon}</p>
<h2>{city}</h2>
<p>{`Current Temp: ${Math.round(temp)} °F`}</p>
<p>{`Wind: ${windDir} ${Math.round(wind)} mph Gusts: ${Math.round(gust)} mph`}</p>
<p>{`Precip: ${Math.round(precip)}in`}</p>
</div>
)
}
export default Weather;
1条答案
按热度按时间6tr1vspr1#
我想我已经找到了解决办法。把lat作为一个依赖项放在useEffect中似乎已经解决了这个问题。},[lat]);