React 编程新手。我使用 api axios 检索了天气信息。我想做的是,如果用户从下拉列表中选择一个特定的城市,我希望显示该城市的天气信息——老实说,我已经研究过但不确定如何编写代码。 有没有人可以指导我。目前,如果我对一个城市进行硬编码,我会在 api url 上获取天气信息,但我希望用户能够从指定的下拉列表中选择任何位置。 到目前为止我的代码:
import React, { useEffect } from "react";
import axios from "axios";
import "./App.css";
import { useState } from "react";
function App({ searchCities }) {
const [city, setCity] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const url = `https://api.openweathermap.org/data/2.5/weather?q=${searchCities}&units=metric&appid=08acd577f8ab8cabf637f7cd3736a629`;
useEffect(() => {
axios.get(url).then((response) => {
setCity(response.data);
console.log(response.data);
setIsLoading(false);
});
}, [searchCities]);
const [newSearchTerm, setNewSearchTerm] = useState('');
const handleChange = (event) =>{
setNewSearchTerm(event.target.value);
}
const handleSubmit = (event) => {
event.preventDefault();
searchCities(newSearchTerm);
setNewSearchTerm('');
}
if (isLoading) {
return <h2>Still Loading be patient</h2>;
}
return (
<form onSubmit={handleSubmit}>
<div>
<div>
<ul>
<select name="city">
<option value="0">Choose the City</option>
<option value="Dallas">Dallas</option>
<option value="London">London</option>
</select>
<h3>Humidity: {city.main.humidity}</h3>
<h3>Temp: {city.main.temp}</h3>
</ul>
</div>
</div>
</form>
);
}
export default App;
试试这个
import React, { useEffect } from "react";
import axios from "axios";
import { useState } from "react";
function App({ searchCities }) {
const [city, setCity] = useState(null);
const [weatherData, setWeatherData] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const getWeatherData = (selectedCity) => {
if (selectedCity) {
const url = `https://api.openweathermap.org/data/2.5/weather?q=${selectedCity}&units=metric&appid=08acd577f8ab8cabf637f7cd3736a629`;
axios.get(url).then((response) => {
setWeatherData(response.data);
console.log(response.data);
setIsLoading(false);
});
}
};
useEffect(() => {}, [searchCities]);
const [newSearchTerm, setNewSearchTerm] = useState("");
const handleChange = (event) => {
console.log(event.target.value);
setCity(event.target.value);
};
useEffect(() => {
if (city) {
setIsLoading(true);
getWeatherData(city);
}
}, [city]);
const handleSubmit = (event) => {
/* event.preventDefault();
searchCities(newSearchTerm);
setNewSearchTerm(''); */
};
if (isLoading) {
return <h2>Still Loading be patient</h2>;
}
return (
<form onSubmit={handleSubmit}>
<div>
<div>
<ul>
<select name="city" onChange={handleChange}>
<option value="0">Choose the City</option>
<option value="Dallas">Dallas</option>
<option value="London">London</option>
</select>
<h3>Humidity: {weatherData?.main.humidity}</h3>
<h3>Temp: {weatherData?.main.temp}</h3>
</ul>
</div>
</div>
</form>
);
}
export default App;