我想跟踪异步Ajax请求的加载、成功和错误状态。我的商店在加载、成功和错误操作时会发生变化,但react组件只有在成功或错误时才会发生变化。因此,我无法检测反应组件的加载状态。
下面是我的代码的样子:
调度员
var AppDispatcher = assign(new Dispatcher(), {
handleServerAction: function(action) {
var payload = {
source: PayloadSources.SERVER_ACTION,
action: action
};
this.dispatch(payload);
}
});
动作创建者
var ActionCreator = {
loadData: function() {
//Calling Synchronous Action
AppDispatcher.handleServerAction({actionType:ActionTypes.LOAD_DATA});
//Calling Asynchronous Action
ApiClient.getData(function(dataObj) {
AppDispatcher.handleServerAction({actionType:ActionTypes.LOAD_DATA_SUCCESS, dataObj: dataObj});
}.bind(this), function(error) {
AppDispatcher.handleServerAction({actionType:ActionTypes.LOAD_DATA_FAIL, error: error});
}.bind(this));
}
};
API客户
var ApiClient = {
/**
* @param success callback
* @param failure callback
*/
getData : function(success, failure){
$.ajax({
url : '/api/get-data',
dataType: 'json',
success : function(data){
success(data);
},
error : function(jqXHR, textStatus, errorThrown){
failure(errorThrown);
}
});
}
};
AppStore
var _state = {
loading: false,
error : null,
dataObj: {}
};
function persistStoreData(loading, error, response) {
_state.loading = loading;
_state.error = error;
_state.dataObj = response;
}
var AppStore = assign({}, EventEmitter.prototype, {
//writing only few important parts
getState: function(){
return _state;
},
dispatcherIndex: AppDispatcher.register(function(payload) {
var action = payload.action;
switch(action.actionType){
case ActionTypes.LOAD_DATA:
persistStoreData(true, null, {});
break;
case ActionTypes.LOAD_DATA_SUCCESS:
persistStoreData(false, null, action.dataObj);
break;
case ActionTypes.LOAD_DATA_FAIL:
persistStoreData(false, payload.action.error, {});
break;
default:
return true;
}
AppStore.emitChange();
return true; // No errors. Needed by promise in Flux Dispatcher.
)};
反应组件
var AppComponent = React.createClass({
getInitialState: function() {
return AppStore.getState();
},
componentDidMount: function() {
ActionCreator.loadData();//Invoking Action, loading data
AppStore.addChangeListener(this._onChange);
},
componentWillUnmount: function() {
AppStore.removeChangeListener(this._onChange);
},
render: function(){
<div className="panel-body">
{this.state.error ? "Error loading data" : null}
{this.state.loading ? 'Loading...': null}
{this.state.dataObj?'Success': null}
</div>
}
});
我发现解决这个问题的唯一解决方案是,假设加载状态为true,而状态中没有数据,错误状态为false。
所以我在视图组件中的渲染方法看起来像:-
render: function {
return{
(<div>
{Util.isEmpty(this.state.data) && !(this.state.error) ? 'Loading...': null}
</div>);
}