我正在创建一个实时天气更新应用程序,它通过输入城市名称和国家/地区代码来提供有关天气的信息。我正在使用 Reactjs 从 https://openweathermap.org 获取数据应用程序接口(interface)。我很好,从中获取数据没有问题。我正在调用一种状态更改方法,该方法通过用户提供的输入更改城市名称和国家/地区代码的初始状态,并且我的应用程序在单击提交按钮时从 API 获取数据。但是每次输入更改时,应用程序似乎都会获取数据(在看到控制台时),并且在单击提交按钮后,我会根据我设置的初始状态获得初始输出。这是该 API 的示例 http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22
响应可以是 XML 或 JSON。虽然我想要 JSON。这是我的代码:
const PATH_BASE='https://api.openweathermap.org/data/2.5/';
const PATH_WEATHER='weather?q=';
const APPID='&appid=71a134a1be2190f78ba5301defa7e44f';
const DEFAULT_CITY='karachi';
const DEFAULT_CC='pk';
const COMMA=',';
class App extends Component {
constructor(props){
super(props);
this.state={result:null,cityName:DEFAULT_CITY,countryCode:DEFAULT_CC};
this.setResult=this.setResult.bind(this);
this.setCity=this.setCity.bind(this);
this.setCountry=this.setCountry.bind(this);
this.fetchWeatherUpdates=this.fetchWeatherUpdates.bind(this);
this.searchSubmit=this.searchSubmit.bind(this);
}
fetchWeatherUpdates(cityName,countryCode){
fetch(`${PATH_BASE}${PATH_WEATHER}${cityName}${COMMA}${countryCode}${APPID}`)
.then(response=>response.json())
.then(result=>this.setResult(result))
.catch(error=>error);
}
componentDidMount(){
const {cityName,countryCode}=this.state;
this.fetchWeatherUpdates(cityName,countryCode);
}
setResult(result){
this.setState({result:result});
}
setCity(event){
this.setState({cityName:event.target.value});
}
setCountry(event){
this.setState({countryCode:event.target.value});
}
searchSubmit(){
const {cityName,countryCode}=this.state;
this.fetchWeatherUpdates(cityName,countryCode);
}
render() {
const {cityName,countryCode}=this.state;
console.log(this.state.result);
if(!this.state.result){
return (<div>Loading...</div>);
}
return (
<div className="App">
<form onSubmit={this.searchSubmit}>
<input type="text" value={this.state.cityName} onChange={this.setCity}/>
<input type="text" value={this.state.countryCode} onChange={this.setCountry}/>
<button type="submit"> Submit </button>
</form>
<h2>
{this.state.result.weather[0].main}
</h2>
</div>
);
}
}
export default App;
抱歉,代码太长了,但我添加了所有代码,这样可能会帮助您回答并可能会揭示我的愚蠢错误....
最佳答案
componentDidMount
只会在组件挂载时运行,所以如果你使用 setState
它不会再次运行。
您没有阻止浏览器在提交处理程序中的默认行为,即重新加载浏览器。通过阻止它,它不会在提交时重新加载。
示例
class App extends Component {
// ...
searchSubmit(event) {
event.preventDefault();
const { cityName, countryCode } = this.state;
this.fetchWeatherUpdates(cityName, countryCode);
}
// ...
}
关于javascript - Lifecycle 方法是否在 setState 上再次触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51538531/