簡體   English   中英

如何在FLUX中處理Ajax響應

[英]How to handle ajax response in FLUX

我是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
    });
  }

這段代碼實際上行不通,因為函數_fetchComments稱為commentActions.js返回整個承諾。

我想要做的:我想在commentActions.js擺脫Ajax回調函數響應,並將結果傳遞到我的有效載荷對象,然后由調度員在我_fetchComments派遣()函數

最好的方法是什么? 如何獲得對ajax回調函數響應的訪問權限?

您應該分派_fetchComments函數,並在解決該諾言后,調用動作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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM