[英]How to handle ajax response in FLUX
I'm new in FLUX and I have problem how to handle ajax in FLUX. 我是FLUX的新手,但在处理FLUX中的Ajax时遇到问题。
My situation is following : 我的情况如下:
I have file commentAPI.js 我有文件commentAPI.js
//all js files are compiled from coffescript
// fetching all comments from server
_fetchComments: function() {
var promise;
promise = $.ajax({
url: "comments/show",
type: "GET",
dataType: "json"
});
return promise.then(function(response) {
// here should be any action ?
}, function(error) {
return console.log(error);
}); }
Then I have commentActions.js 然后我有commentActions.js
fetchComments: function () {
allcomments=commentAPI._fetchComments();
return Dispatcher.dispatch({
actionType: ActionTypes.ALL_COMMENTS,
comments: allcomments
});
}
This code actually doesnt work because function _fetchComments called in commentActions.js return whole promise. 这段代码实际上行不通,因为函数_fetchComments称为commentActions.js返回整个承诺。
What I want to do: I would like to get response from ajax callback function and pass the result to my payload object and then dispatch it by Dispatcher in my _fetchComments() function in commentActions.js 我想要做的:我想在commentActions.js摆脱Ajax回调函数响应,并将结果传递到我的有效载荷对象,然后由调度员在我_fetchComments派遣()函数
How is the best way to do it? 最好的方法是什么? How can I get the access to the ajax callback function response ?
如何获得对ajax回调函数响应的访问权限?
You should dispatch _fetchComments function and when that promise is resolved, invoke the action fetchComments . 您应该分派_fetchComments函数,并在解决该诺言后,调用动作fetchComments 。
In the react code you should invoke the async function (ie _fetchComments ). 在react代码中,您应该调用async函数(即_fetchComments )。
In your example: 在您的示例中:
// fetching all comments from server
_fetchComments: function() {
var promise;
promise = $.ajax({
url: "comments/show",
type: "GET",
dataType: "json"
});
return promise.then(function(response) {
// put the sync action here
fetchComments(response)
}, function(error) {
return console.log(error);
}); }
And don't forget to remove it from the action (ie fetchComments ) 并且不要忘记将其从操作中删除(即fetchComments )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.