问题描述
我想通过°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
。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)