在通量架构中,谁是负责发送更新到服务器?(In the flux architecture, who

2019-10-21 05:51发布

因此,在磁通量架构,数据如下流动:

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

所以我们说的观点是一个评论框。 当用户提交一个评论,一个addComment动作被触发,但应该在哪里这一评论被发送到服务器? 如果它发生在动作的功能,调度它之前,还是应该商店接收到调度员的行动时,这样做呢?

这两种情况缝像违反了单一职责模式。 还是说有两个CommentStores,一个LocalCommentStore并且这两个处理addComment行动ServerCommentStore?

Answer 1:

你的情况是行动既负责发送未决诉讼或乐观更新的存储和发送到的WebAPI的电话:

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

onWebAPISuccess -> Dispatcher -> Store -> emitEvent -> View
onWebAPIFail -> Dispatcher -> Store -> emitEvent -> View


Answer 2:

这是一个很好的问题。 下面是我如何做到这一点。

我创造了我的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>
    }
});


文章来源: In the flux architecture, who is responsible for sending updates to the server?