如何在FLUX中处理ajax响应

How to handle ajax response in FLUX

本文关键字:处理 ajax 响应 FLUX      更新时间:2023-09-26

我是FLUX的新手,我有问题如何处理FLUX中的ajax。

我的情况如下:

我有文件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);
        });   }
然后我有commentActions.js
   fetchComments: function () {
    allcomments=commentAPI._fetchComments(); 
    return Dispatcher.dispatch({
      actionType: ActionTypes.ALL_COMMENTS,
      comments: allcomments
    });
  }

这段代码实际上不起作用,因为在commentActions.js中调用的函数_fetchComments返回整个承诺。

我想做的是:我想从ajax回调函数中获得响应,并将结果传递给我的有效载荷对象,然后通过Dispatcher在commentActions.js

中的_fetchComments()函数中调度它

做这件事的最好方法是什么?我如何获得访问ajax回调函数响应?

你应该调度_fetchComments函数,当promise被解析后,调用fetchComments操作。

在react代码中你应该调用async函数(即_fetchComments)。

在你的例子中:

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

不要忘记从动作中删除它(即fetchComments)