【发布时间】:2017-08-10 07:49:27
【问题描述】:
我正在编写一个简单的应用程序,它需要从 API 获取一些天气数据。端点。 我对 React 很陌生,所以这可能是我不了解如何在 React 中使用 Promise。
这是我的代码:
var React = require('react');
var Weather = React.createClass({
getInitialState: function() {
console.log('GetInitialState', 'info');
return {
foo : 1,
weatherConditions : "No weather data"
};
},
update: function() {
console.log('Updating State', 'primary');
let self = this;
function httpRequestWeather(url) {
return new Promise(function(resolve, reject) {
var weatherRequest = new XMLHttpRequest();
weatherRequest.open("GET", url, true);
weatherRequest.onreadystatechange = function() {
if ( this.status === 200) {
console.log("request finished and response is ready");
console.log(this.response);
// only returns when I post code here
self.setState({
weatherConditions: this.response
});
resolve(this.response);
} else{
reject(new Error("no weather data"));
}
};
weatherRequest.send();
});
}
httpRequestWeather("www.weatherendpoint.con/json").then(function(responseText){
let text = JSON.parse(responseText);
//never gets triggered
self.setState({
weatherConditions: "Hi"
});
}).catch(function(){
//always triggered
self.setState({
weatherConditions: "Buy"
});
});
this.setState({foo: 2});
},
render: function() {
console.log('Render', 'success');
let condition = this.state.weatherConditions;
return (
<div>
<span>{condition} </span>
<span>{this.state.foo} </span>
</div>
)
},
componentWillMount: function() {
console.log('ComponentWillMount', 'warning');
this.update();
},
componentDidMount: function() {
console.log('ComponentDidMount', 'warning');
this.update();
},
shouldComponentUpdate: function() {
console.log('ShouldComponentUpdate', 'info');
return true;
}
});
module.exports = Weather;
基本上,问题是在这个函数中我必须触发 self.setState({weatherConditions: this.response});
function httpRequestWeather(url) {
return new Promise(function(resolve, reject) {
var weatherRequest = new XMLHttpRequest();
weatherRequest.open("GET", url, true);
weatherRequest.onreadystatechange = function() {
if ( this.status === 200) {
console.log("request finished and response is ready");
console.log(this.response);
// only returns when I post code here
self.setState({
weatherConditions: this.response
});
resolve(this.response);
} else{
reject(new Error("no weather data"));
}
};
weatherRequest.send();
});
}
如果我尝试在 promise resolve 上设置状态,我总是无法解决。
httpRequestWeather("www.weatherendpoint.con/json").then(function(responseText){
let text = JSON.parse(responseText);
//never gets triggered
self.setState({
weatherConditions: "Hi"
});
}).catch(function(){
//always triggered
self.setState({
weatherConditions: "Buy"
});
我做错了什么?谢谢!
【问题讨论】:
标签: javascript ajax reactjs promise es6-promise