flux:如何从商店内部更新商店

flux: how to update a store from within a store

我的用例很简单。我想向我的 NotificationStore 添加一条通知消息,以便在我的主要商店已成功更新时向用户显示信息横幅。

实现此目的的最简单方法似乎是从我的主要商店中发起操作:

   onSaveRule: function() {
        localStorage.setItem("rule", JSON.stringify(_state));
        action.fire("rule successfully saved!"); //mutates NotificationStore
    },

但是,action.fire 行抛出以下 运行 时间异常:

不变违规:Dispatch.dispatch(...):无法在调度过程中调度。

显然,从商店内部调用操作是一种反模式。那么怎样才能达到预期的效果呢?

storeAstoreB 为例,您最初的想法是让 storeA 触发 action 并让 storeB 收听相同 action.

与其在 storeA 内直接触发 action,不如让 storeB 直接监听 storeA 状态变化 triggers。意思是在 storeA 状态发生变化并调用 trigger 通知您的 components 时,storeB 也将被相同的 trigger 通知。 storeB 然后可以调用 gettersstoreA 检索新状态。

在此模式中,storeBstoreA 派生商店 。这保留了 单向数据流 flux 模式的哲学。