【发布时间】:2020-06-30 21:16:24
【问题描述】:
我正在使用 OpenWeatherMapAPI 来获取当前天气(API 密钥被隐藏)。 这个想法是获取值并将其作为道具传递以在不同的组件中呈现。 我尝试了几种方法,但无法显示响应中的值。
响应是有效的,因为我在 jsonlint 上检查过。
我收到一个未定义的错误。
const [city, setCity] = useState();
let currentWeather;
{
// UseEffect to run the effect during initial render
useEffect(() => {
axios
.get(baseUrl + city + ",IN&APPID=" + APPKey + "&units=metric")
.then((res) => {
currentWeather = res.data;
});
// fetch(baseUrl + city + ",IN&APPID=" + APPKey + "&units=metric");
}, []);
}
const handleInputChanges = (e) => {
setCity(e.target.value);
};
const resetSearchValue = () => {
setCity("");
};
const fetchWeather = async (e) => {
e.preventDefault();
{
{
axios
.get(baseUrl + city + ",IN&APPID=" + APPKey + "&units=metric")
.then((res) => {
currentWeather = res.data;
console.log("weather", currentWeather);
});
}
}
resetSearchValue();
};
return (
<Container className="themed-container" fluid="sm">
<InputGroup className="search">
<Input
placeholder="Enter a city in India"
value={city}
onChange={handleInputChanges}
/>
<InputGroupAddon addonType="append">
<Button color="secondary" onClick={fetchWeather}>
Check
</Button>
</InputGroupAddon>
// for testing the output
<h1>{currentWeather.sys.country}</h1>
</InputGroup>
//the object wil be passed as props to other component for rendering the
result
<FetchWeather search={currentWeather} />
</Container>
);
};
export default Searchbar;
OpenWeatherAPI 响应
JSON : {"coord":{"lon":77.6,"lat":12.98},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"base":"stations","main":{"temp":297.51,"feels_like":301.13,"temp_min":295.15,"temp_max":302.04,"pressure":1010,"humidity":100},"visibility":6000,"wind":{"speed":3.45,"deg":206},"clouds":{"all":75},"dt":1593102591,"sys":{"type":1,"id":9205,"country":"IN","sunrise":1593044734,"sunset":1593091128},"timezone":19800,"id":1277333,"name":"Bengaluru","cod":200}
【问题讨论】:
-
这能回答你的问题吗? stackoverflow.com/questions/55424405/…
标签: reactjs