我是 ReactJs 的新手,所以不要评判我。我正在练习在 ReactJs 中写下一些小应用程序。我的应用程序的主要目的是从 weather api 获取 json 数据,并应该在网络浏览器中显示它。但是当我搜索存在的城市时它可以正常工作并正确显示到浏览器中如果我检查空白数据我无法从浏览器中删除我以前的数据。如果搜索值为零,我如何让它消失。
我的主 App.js
import React from "react";
import Forms from "./components/Form";
import Weather from "./components/Weather"
class App extends React.Component{
state = {
temp:undefined,
city:undefined,
country:undefined,
sunrise:undefined,
sunset:undefined,
error:undefined
};
gettingWeather = async (e) =>{
e.preventDefault();
const city = e.target.elements.city.value;
if(city)
{
const api = await
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=aea3bfae005c93e040ec823207545968`);
const data = await api.json();
if(data.cod != "404")
{
var date = new Date();
date.setTime(data.sys.sunrise);
var sunS = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
this.setState({
temp:data.main.temp,
city:data.name,
country:data.sys.country,
sunrise:sunS,
error:""
});
}
}else{
this.city = undefined;
console.log("PUSTOY");
this.setState = {
temp:undefined,
city:undefined,
country:undefined,
sunrise:undefined,
sunset:undefined,
error:undefined
};
}
}
render(){
return (
<div>
<Forms weatherMethod = {this.gettingWeather}/>
<Weather
temp = {this.state.temp}
city = {this.state.city}
country = {this.state.country}
sunRise = {this.state.sunrise}
/>
</div>
);
}
}
export default App;
我从 From.js 获得点击并显示在天气表单中
表单.js
import React,{Component} from "react";
class Yozuvla extends Component{
render(){
return(
<form onSubmit={this.props.weatherMethod}>
<br/>
<input type="text" name="city" placeholder="Tashkent"/>
<button>Get weather</button>
</form>
);
}
}
export default Yozuvla;
我的浏览器在这里显示 View
import React from "react"
class Weather extends React.Component{
render(){
if(this.props.city){
console.log(this.props.city.length);
return(
<div>
<p>Temperatura: {this.props.temp}</p>
<p>Shahar: {this.props.city}</p>
<p>Davlat: {this.props.country}</p>
<p>Kun otishi: {this.props.sunRise}</p>
</div>
);
}else{
return(
<div>
<h1>BLANK for begin</h1>
</div>
);
}
}
}
export default Weather;
对于 begin BLANK for begin 会出现,但是当我搜索现有城市时,这个 BLANK for begin** 并且我尝试使用不存在的城市,这个 p tegs 永远不会消失。我可以在这里做什么??
最佳答案
在 gettingWeather
内的 else
block 中,您正在将 this.setState
重新分配给一个对象,而不是调用它
this.setState = { // <------ reassigning instead of calling
temp: undefined,
city: undefined,
country: undefined,
sunrise: undefined,
sunset: undefined,
error: undefined
};
改为调用它
this.setState({
temp: undefined,
city: undefined,
country: undefined,
sunrise: undefined,
sunset: undefined,
error: undefined
});
关于javascript - 无法在 else 语句中呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57643287/