React API调用不会更改状态
问题描述:
我正在尝试创建React天气应用程序。在这个应用程序,你可以键入城市的名称,它显示当前的温度。 但caloing API后,我的状态不想更改为其他城市对象(在coponentDidMount方法 - “obje”状态)。React API调用不会更改状态
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;
答
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;
控制台中是否有任何错误? –
没有错误发生 – Mac