我正在尝试创建React天气应用。在此应用程序中,您可以键入城市名称,并显示当前温度。 但是在获得API之后我的状态不想改变到其他城市对象(在coponentDidMount方法中 - “obje”状态)。
import React, { Component } from 'react';
import Api from './api.js';
class App extends Component {
constructor(props) {
super(props);
this.state = {
obje: {},
inputValue: 'Paris'
}
}
componentDidMount() {
var rootUrl = "http://api.openweathermap.org/data/2.5/weather?q=";
var city = this.state.inputValue
var key = "&appid=aa32ecd15ac774a079352bfb8586336a";
fetch(rootUrl + city + key)
.then(function(response) {
return response.json();
}).then(d => {
this.setState({obje:d})
});
}
handleChange(event) {
event.preventDefault();
this.setState({inputValue: this.refs.inputVal.value});
console.log(this.refs.inputVal.value);
}
render() {
return (
<div>
{this.state.obje.name}
<form action="" method="" onSubmit={this.handleChange.bind(this)}>
<input ref="inputVal" type="text" />
<input type="submit" />
</form>
</div>
);
}
}
export default App;
答案 0 :(得分:1)
componentDidMount
仅在组件安装时调用一次。状态更改不会再次触发该代码,因此不会再次发出XHR请求。将XHR逻辑拆分为自己的方法并在两个地方调用它,例如:
import React, { Component } from 'react';
import Api from './api.js';
class App extends Component {
constructor(props) {
super(props);
this.state = {
obje: {},
inputValue: 'Paris'
}
}
getWeather() {
var rootUrl = "http://api.openweathermap.org/data/2.5/weather?q=";
var city = this.state.inputValue;
var key = "&appid=aa32ecd15ac774a079352bfb8586336a";
fetch(rootUrl + city + key)
.then(function(response) {
return response.json();
}).then(d => {
this.setState({obje:d})
});
}
componentDidMount() {
this.getWeather();
}
handleChange(event) {
event.preventDefault();
this.setState({inputValue: this.refs.inputVal.value}, () => {
this.getWeather();
});
console.log(this.refs.inputVal.value);
}
render() {
return (
<div>
{this.state.obje.name}
<form action="" method="" onSubmit={this.handleChange.bind(this)}>
<input ref="inputVal" type="text" />
<input type="submit" />
</form>
</div>
);
}
}
export default App;