Flux - 在Store寄存器之前调度的操作

时间:2016-03-01 10:06:46

标签: javascript ajax reactjs flux reactjs-flux

我正在构建一个使用flux作为模式的应用程序。 我正在尝试在进行API调用时添加一个加载器(微调器),但它不起作用,我想我错过了一些东西。 流程如下: 加载应用程序时我正在调用initApp

var InitActions = {
initApp: function(){
    FooActions.getFoo();
}};
module.exports = InitActions;

FooActions调度GET_FOO Action并调用APIService.foo.getFooByUser

var FooActions = {

getFoo: function(){
    var account = accountStore.getAccountData();
    var accountId = account.id;
    Dispatcher.dispatch({
        actionType: ActionTypes.GET_FOO
    });
   APIService.foo.getFooByUser(accountId);
}};
module.exports = FooActions;

APIService将进行ajax调用并作为响应将触发ServerActions.getFooSuccess或ServerActions.getFooFailed操作

var APIService = {
    foo: {
       getFooByUser : function(accountId){

        var url = apiUrl;
        var params = {
            "accountId":accountId
        };
       promise.post(url,params)
           .then(function(response){
                ServerActions.getFooSuccess(response);
            })
           .catch(function(response){
                ServerActions.getFooFailed(response);
            });
        }
    }
}; 
module.exports = APIService;

ServerActions将调度GET_FOO_SUCCESS或GET_FOO_Failed

var ServerActions = {
getFooSuccess: function(response){
    Dispatcher.dispatch({
        actionType: ActionTypes.GET_FOO_SUCCESS,
        foo: response
    });
},

getFooFailed: function(response){
    Dispatcher.dispatch({
        actionType: ActionTypes.GET_FOO_FAILED
    });
}
}

并且foo商店正在通过dispatcher.register

监听这些事件
var FooStore = assign({}, EventEmitter.prototype,{...};
Dispatcher.register(function(action){
switch (action.actionType){
    case ActionTypes.GET_FOO:
        _isLoading = true;
        FooStore .emitChange();
        break;
    case ActionTypes.GET_FOO_SUCCESS:
        _isLoading = false;
        _foo = action.foo;
        FooStore .emitChange();
        break;
    case ActionTypes.GET_FOO_FAILED:
        _isLoading = false;
        FooStore.emitChange();
        break;
    default:
    // do nothing
}});

现在,根据_isLoading参数,我知道何时在我的foo组件中显示和隐藏加载器。由于某种原因,代码永远不会到达GET_FOO案例,尽管此操作是在API调用之前调度的。 有人可以告诉我为什么吗?

编辑: 当我调试调度程序的代码时,我可以在调度函数中看到循环

Dispatcher.prototype.dispatch = function dispatch(payload) {
    !!this._isDispatching ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.') : invariant(false) : undefined;
    this._startDispatching(payload);
    try {
      for (var id in this._callbacks) {
        if (this._isPending[id]) {
          continue;
        }
        this._invokeCallback(id);
      }
    } finally {
      this._stopDispatching();
    }
  };

我可以看到FooStore尚未注册为调度程序回调。 如何在触发任何操作之前确保它已被注册?

1 个答案:

答案 0 :(得分:0)

解决: 我确定FooStore是在任何阳离子之前注册的,因为在我呼叫initApp()

之前要求它