Javascript 承诺解决操作在ReactJS应用程序中延迟触发
我正在编写一个简单的应用程序,需要从API获取一些天气数据。终点。 我对React非常陌生,所以这可能是因为我不了解React中如何使用承诺 这是我的密码:Javascript 承诺解决操作在ReactJS应用程序中延迟触发,javascript,ajax,reactjs,promise,es6-promise,Javascript,Ajax,Reactjs,Promise,Es6 Promise,我正在编写一个简单的应用程序,需要从API获取一些天气数据。终点。 我对React非常陌生,所以这可能是因为我不了解React中如何使用承诺 这是我的密码: var React = require('react'); var Weather = React.createClass({ getInitialState: function() { console.log('GetInitialState', 'info'); return { foo :
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;
如果我试图设定承诺解决的状态,我总是无法解决
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"
});
我做错了什么?谢谢 执行请求时出现错误。您应该首先检查错误,看看为什么会得到它,并根据它为错误流设置适当的状态
httpRequestWeather("www.weatherendpoint.con/json")
.then(function(responseText){
let text = JSON.parse(responseText);
self.setState({
weatherConditions: "Hi"
});
}).catch(function(err){
console.log('Error on request:', err);
self.setState({
error: err
});
});
如果要调用self.setState。。。在成功和错误条件下,以下模式可能有用:
asyncRequest()
.then(function(data) {
return { /* properties */ }; // state object (success)
}, function(err) {
console.log(err);
return { /* properties */ }; // state object (something suitable to describe an error)
})
.then(self.setState);
所以你可以在这里写:
httpRequestWeather() // pass url if necessary
.then(function(weatherData) { // make sure `httpRequestWeather()` delivers data, not a JSON string.
return {
'weatherConditions': weatherData,
'error': null
};
}, function(err) {
console.log('Error on request:', err); // optional
return {
'weatherConditions': 'unknown',
'error': err
}
})
.then(self.setState);
上面的特定属性只是我的想法,可能有用,并且可以根据self.setState和/或self.render的期望进行调整。例如,错误属性可能是不必要的 非常感谢!那有帮助!我现在正在做这件事,还有一个问题:。你介意帮忙吗?@margarita仅供参考,React.createClass将在下一个主要版本中被弃用。他们正计划将其拉到一个单独的包中,以便在16.0.0发布后仍然可以使用。您可以使用ES6类来构建有状态组件。更多信息:谢谢!我来看看!
httpRequestWeather() // pass url if necessary
.then(function(weatherData) { // make sure `httpRequestWeather()` delivers data, not a JSON string.
return {
'weatherConditions': weatherData,
'error': null
};
}, function(err) {
console.log('Error on request:', err); // optional
return {
'weatherConditions': 'unknown',
'error': err
}
})
.then(self.setState);