如何解决我无法使React挂钩切换按钮在摄氏和华氏度之间切换?
我想通过°C上的onClick按钮在摄氏温度和华氏温度之间切换,该按钮可以同时将main.temp值max_temp和min_temp转换为华氏温度。
Weather.js
import React,{ useState,useEffect } from 'react';
import Homepage from './Homepage';
function Weather() {
const API_KEY = 'b78ffacf63ad995ef34f6811b0e06433';
const [localweather,setLocalweather] = useState([]);
const [query,setQuery] = useState("");
//geolocation to get the local weather
const getLonLat = () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
const lon = position.coords.longitude;
const lat = position.coords.latitude;
fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&units=metric&appid=${API_KEY}`)
.then(response => response.json())
.then(result => {
setLocalweather(result)
return;
})
.catch(err => console.log(err));
})
}
}
useEffect(() => {
getLonLat();
},[])
//give input to get other location weather
const searchInput = (e) => {
e.preventDefault()
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${query}&units=metric&appid=${API_KEY}`)
.then(response => response.json())
.then(result => {
setLocalweather(result)
setQuery("")
})
.catch(err => console.log(err));
}
return (
<Homepage
localweather={localweather}
getLonLat={getLonLat}
searchInput={searchInput}
setQuery={setQuery} />
)
}
export default Weather;
Homepage.js
import React,{ useState } from 'react';
function Homepage(props) {
return (
<div>
<h3>{props.localweather.main && props.localweather.main.temp} °C</h3>
<span>{props.localweather.main && props.localweather.main.temp_min} °C</span>
<span>{props.localweather.main && props.localweather.main.temp_max} °C</span>
</div>
)
}
export default Homepage;
我试图将props.localweather.main && props.localweather.main.temp
放在usestate()
上,但它给出了undefined
。
解决方法
您从API调用获得的响应很可能不是数组,而是一个对象。另外,由于API调用是异步的,因此您的localweather
状态将不会立即具有您要查找的那些属性,这就是为什么会出现undefined
错误的原因。通常的做法是在您的渲染器中使用&&
而不是useState
来检查空值,以消除此问题。
首先,您需要将[]
中的{}
从空的初始值useState
更改为:
const [localweather,setLocalweather] = useState({});
然后,您可以通过以下方式进行null
或undefined
的检查:
return (
{
props.localweather &&
props.localweather.main &&
<div>
<h3>{props.localweather.main.temp} °C</h3>
<span>{props.localweather.main.temp_min} °C</span>
<span>{props.localweather.main.temp_max} °C</span>
</div>
}
)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。