0
我正在嘗試製作具有反應的天氣應用程序,並且我想通過在input
中輸入城市的name
來更改城市。我有一個必須改變的狀態函數:ReactJS更改網址
update(e){
this.setState({cityName: e.target.value})
}
而在渲染功能,我有這樣的:
return <div id="layout-content" className="layout-content-wrapper">
<input type="text"
onChange={this.update.bind(this)}/>
<div className="panel-list">{ persons }</div>
<h1>{this.state.coord.lon}</h1>
<h1>{this.state.cityName}</h1> //output my city name
而且我有函數,我通過我的城市名稱中的var網址API:
UserList(city = this.state.cityName){
let apiKey = 'c24bda9c5812d6be82860b70c35d41a5';
let url = 'http://api.openweathermap.org/data/2.5/weather?q=';
let weatherURL = 'http://api.openweathermap.org/data/2.5/weather?q='+city+'&appid=c24bda9c5812d6be82860b70c35d41a5';
return $.getJSON(weatherURL).then((response) => {
this.setState({coord: response.coord});
this.setState({person: response.weather});
});
}
</div>
但它不改變天氣預報。爲什麼它沒有改變? 所有代碼:
class App extends React.Component {
constructor(props){
super();
this.state = {
person: [],
coord: [],
cityName: 'London'
};
}
componentDidMount() {
this.UserList();
}
update(e){
this.setState({cityName: e.target.value})
}
UserList(city = this.state.cityName){
let apiKey = 'c24bda9c5812d6be82860b70c35d41a5';
let url = 'http://api.openweathermap.org/data/2.5/weather?q=';
let weatherURL = 'http://api.openweathermap.org/data/2.5/weather?q='+city+'&appid=c24bda9c5812d6be82860b70c35d41a5';
return $.getJSON(weatherURL).then((response) => {
this.setState({coord: response.coord});
this.setState({person: response.weather});
});
}
render() {
const persons = this.state.person.map((item) => {
return <div>
<h1>{item['id']}</h1>
<span>{item['main']}</span>
</div>
});
return <div id="layout-content" className="layout-content-wrapper">
<input type="text"
onChange={this.update.bind(this)}/>
<div className="panel-list">{ persons }</div>
<h1>{this.state.coord.lon}</h1>
<h1>{this.state.cityName}</h1>
</div>
}
}
export default App;