gpt4 book ai didi

javascript - setState 在单独文件中的非 React 组件中

转载 作者:行者123 更新时间:2023-12-03 08:46:30 24 4
gpt4 key购买 nike

向后端执行一些 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 文件。那么连接它们并更新状态的正确方法是什么。

最佳答案

正如菲利克斯建议检查:How do I return the response from an asynchronous call?

做了一个回调函数并且它有效

../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>
);
}
});

关于javascript - setState 在单独文件中的非 React 组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32869459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com