我在const city未处理拒绝(TypeError)中遇到错误:无法读取未定义的属性'value'
handleClick = async(e) => {
e.preventDefault();
const city = e.target.elements.city.value;
const api=await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=563f12881628bc03a04f230c259dd4f9`);
const rtr = await api.json();
this.setState({
temperature:rtr.main.temp,
humidity:rtr.main.humidity,
city:rtr.name,
country:rtr.sys.country
});
}
期望通过api调用来获取城市
答案 0 :(得分:0)
您应该添加if语句以检查城市是否存在。
handleClick = async(e) => {
e.preventDefault();
const city = !!e.target.elements.city && e.target.elements.city.value;
if (!city) {
return;
}
const api=await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=563f12881628bc03a04f230c259dd4f9`);
const rtr = await api.json();
this.setState({
temperature:rtr.main.temp,
humidity:rtr.main.humidity,
city:rtr.name,
country:rtr.sys.country
});
}