1

所以在flux架构中,数据流如下:

View -> Action -> Dispatcher -> Store
 ^ <-----------------------------|

所以假设视图是一个评论框。当用户提交评论时,会触发 addComment 操作,但是该评论应该发送到服务器的哪里呢?它应该发生在动作函数中,在调度它之前,还是商店应该在从调度程序接收到动作时执行它?

这两种情况似乎都违反了单一责任模式。还是应该有两个 CommentStore,一个 LocalCommentStore 和一个 ServerCommentStore 都处理 addComment 操作?

4

2 回答 2

6

在您的情况下,Action 负责向商店发送待处理的操作或乐观更新并发送对 WebAPI 的调用:

View -> Action -> Pending Action or optimistic update  -> Dispatcher -> Store -> emitEvent -> View 
               -> WebUtils.callAPI()

onWebAPISuccess -> Dispatcher -> Store -> emitEvent -> View
onWebAPIFail -> Dispatcher -> Store -> emitEvent -> View
于 2014-11-08T12:26:54.237 回答
4

这是一个很好的问题。这是我的做法。

我为我的 API 创建了一个模块。我将该模块导入到 actions.js 中,然后将 API 响应发送到我的商店。这是一个示例(使用fluxxor),我的应用程序中带有我的API调用的商店可能看起来像:

# actions.js
var MyAPI = require('./my-api'),
    Constants = require('./constants/action-constants');

module.exports = {
    doSomeCrazyStuff: function(stuff, userID) {
        MyAPI.doSomeCrazyStuff(stuff, userID)
             .success(function(resp) {
                 this.dispatch(Constants.DO_CRAZY_STUFF_SUCCESS, {stuff: resp.stuff});
                 if (resp.first_stuff_did) {
                     this.dispatch(Constants.SHOW_WELCOME_MESSAGE, {msg: resp.msg});
                 }
             })
             .error(function(e) {
                 this.dispatch(Constants.DO_CRAZY_STUFF_ERROR, {e: resp.error});
             });
    }
};

# store.js
var Fluxxor = require('fluxxor'),
    ActionConstants = require('./constants/action-constants');

var StuffStore = module.exports = {
    Fluxxor.createStore({
        initialize: function() {
            this._bindActions();
            this.stuff = null;
        },
        _bindActions: function() {
            this.bindActions(
                ActionConstants.DO_CRAZY_STUFF_SUCCESS, this.handleDoCrazyStuffSuccess
            );
        },
        handleDoCrazyStuffSuccess: function(payload) {
            this.stuff = payload.stuff;
            this.emit('change');
        }
   });
}

# stuff-component.js
var React = require('react'),
    Fluxxor = require('fluxxor'),
    FluxMixin = Fluxxor.FluxMixin(React),
    StoreWatchMixin = Fluxxor.storeWatchMixin;

var StuffComponent = module.exports = React.createClass(function() {
    mixins: [FluxMixin, StoreWatchMixin("StuffStore")],
    getStateFromFlux: function() {
        flux = this.getFlux();

        var StuffStore = flux.store("StuffStore").getState();

        return {
            stuff: StuffStore.stuff
        }
    },
    onClick: function() {
        this.getFlux().actions.doSomeCrazyStuff();
    },
    render: function() {
        return <div onClick={this.onClick}>{this.state.stuff}</div>
    }
});
于 2014-12-18T07:33:28.070 回答