我正在从API获取数据并使用Loader进行条件渲染。有时所有数据都显示在页面上,但通常Loader只显示数据而不显示数据。我不明白为什么会这样。
看起来问题通常发生在智能手机上,而不是电脑上。
useEffect(() => {
navigator.geolocation &&
navigator.geolocation.getCurrentPosition((position) => {
axios
.get(
`https://api.openweathermap.org/data/2.5/weather?lat=${position.coords.latitude}&lon=${position.coords.longitude}&appid=${process.env.REACT_APP_WEATHER_API_KEY}&units=${metric_units}`
)
.then((response) => {
console.log(response.data);
setData(response.data);
})
.catch((error) => {
alert('Network Error');
console.error('API call error:', error);
});
});
字符串
},[]);
let localDay = new Date((data.dt + data.timezone) * 1000).getUTCDay();
let localDate = new Date((data.dt + data.timezone) * 1000).getUTCDate();
let localMonth = new Date((data.dt + data.timezone) * 1000).getUTCMonth();
let localHours = new Date((data.dt + data.timezone) * 1000).getUTCHours();
let localMinutes = new Date((data.dt + data.timezone) * 1000).getUTCMinutes();
{Object.keys(data).length === 0 ? (
<PuffLoader color={'#ffffff'} size={200} className='loader' />
) : (
<div className='content'>
{/* ********** TOP-SECTION ********** */}
<section className='top-section'>
<div className='location'>
<p>{data.name}</p>
{data.sys && <p>, {data.sys.country}</p>}
</div>
<div className='date-time'>
{
<p className='date'>
{weekdays[localDay]}, {months[localMonth]} {localDate}
</p>
}
{
<p className='time'>
{localHours < 10 ? '0' + localHours : '' + localHours}:
{localMinutes < 10 ? '0' + localMinutes : '' + localMinutes}
</p>
}
</div>
<div className='temp-icon'>
<div className='temp'>
{data.main && <h1>{data.main.temp.toFixed()} °C</h1>}
</div>
<div className='icon-div'>
{data.weather && (
<img
className='icon'
src={`http://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`}
alt='weather icon'
></img>
)}
</div>
<div className='description'>
{data.weather && <p>{data.weather[0].description}</p>}
</div>
</div>
<div className='description-feels-like'>
<div className='feels-like'>
{data.main && (
<p>Feels like {data.main.feels_like.toFixed()} °C</p>
)}
</div>
</div>
</section>
{/* ********** BOTTOM-SECTION ********** */}
{data.name !== undefined && (
<section className='bottom-section'>
<div className='humidity'>
{data.main && <p className='bold'>{data.main.humidity} %</p>}
<p>Humidity</p>
</div>
<div className='pressure'>
{data.main && <p className='bold'>{data.main.pressure} mb</p>}
<p>Pressure</p>
</div>
<div className='wind'>
{data.wind && (
<p className='bold'>{data.wind.speed.toFixed()} m/s</p>
)}
<p>Wind</p>
</div>
</section>
)}
</div>
)}
型
1条答案
按热度按时间oknwwptz1#
发生这种情况是因为您没有向useEffect传递任何依赖项,并且它在页面加载中只工作一次,因此您需要将
setData
作为依赖项传递给useEffect。字符串