【发布时间】:2019-09-01 13:21:18
【问题描述】:
我需要有关我的 React 天气应用程序的帮助。我正在寻找一个城市以从 API 获取天气预报。一切正常。当我输入城市名称并搜索时,会出现结果。但是我想在获得结果时清除输入文本。我做了以下resetForm,它正在清除输入字段,但同时清除API的结果。
class Form extends React.Component{
render(){
resetForm = () => {
this.refs.inputId.value="";
}
return(
<form onSubmit={this.props.getWeather}>
<input type="text" name="city" placeholder="Type a city name..." ref="inputID" />
<button>Search</button>
</form>
);
}
};
getWeather = async (e) =>{
this.setState({loading: true});
e.preventDefault();
const city = e.target.elements.city.value;
const api_call = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`);
const data = await api_call.json();
if(city){
console.log(data);
this.setState({
temperature: data.main.temp,
city: data.name,
humidity: data.main.humidity,
description: data.weather[0].description,
error: "",
loading:false,
});
}else{
this.setState({
temperature: undefined,
city: undefined,
humidity: undefined,
description: undefined,
error: "Please enter the city and the country name!",
loading:false,
});
}
【问题讨论】: