我不能让React挂钩切换按钮在celcius和farenheit之间切换



我想在摄氏度和华氏度之间切换,在°C上点击一个按钮,它可以同时转换为我的主温度值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;

主页.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({});

然后您可以将nullundefined检查为:

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>
}
)

相关内容

  • 没有找到相关文章

最新更新