做一些xhr请求到后端,我希望我所有的请求都在一个单独的文件是WebAPIUtils.js
../utils/WebAPIUtils.js
var request = require('superagent');
var constants = require('../constants/constants');
var APIEndPoints = constants.APIEndPoints;
module.exports = {
loadPost: function() {
request.get(APIEndPoints.USER + '/' + 'ahmadajmi')
.set('Accept', 'application/json')
.end(function(error, res) {
if (res) {
var json = JSON.parse(res.text);
return json;
}
});
}
};
post.js
var React = require('react');
var WebAPIUtils = require('../utils/WebAPIUtils');
// other requires
var Post = React.createClass({
getInitialState: function() {
return {data: ''}
}
,
componentDidMount: function() {
// Want to setState like this
// this.setState({data: WebAPIUtils.loadPost()});
// instead of this
this.loadPost();
}
,
// this method is working fine here, but I want to use the one in `WebAPIUtils.js` file
loadPost: function() {
request.get(APIEndPoints.USER + '/' + 'ahmadajmi')
.set('Accept', 'application/json')
.end(function(error, res) {
if (res) {
var json = JSON.parse(res.text);
this.setState({data: json})
}
}.bind(this));
},
render: function() {
return (
<div className="post">
{this.state.data}
</div>
);
}
});
上面的代码工作得很好,但是我想把我所有的xhr请求移动到WebAPIUtils.js
文件。那么,连接它们并更新状态的正确方法是什么呢?
菲利克斯建议检查:我如何从异步调用返回响应?
做了一个回调函数,它工作
../utils/WebAPIUtils.js
var request = require('superagent');
var constants = require('../constants/constants');
var APIEndPoints = constants.APIEndPoints;
module.exports = {
// Add callback
loadPost: function(callback) {
request.get(APIEndPoints.USER + '/' + 'ahmadajmi')
.set('Accept', 'application/json')
.end(function(error, res) {
if (res) {
var json = JSON.parse(res.text);
callback(json);
}
});
}
};
post.js
var React = require('react');
var WebAPIUtils = require('../utils/WebAPIUtils');
var Post = React.createClass({
getInitialState: function() {
return {data: ''}
}
,
componentDidMount: function() {
// Execute loadPost and setState based on the returned data
WebAPIUtils.loadPost(function(result) {
this.setState({data: result})
}.bind(this));
}
,
render: function() {
return (
<div className="post">
{this.state.data}
</div>
);
}
});