【问题标题】:What's the best way to declare global actions in Mobx-State-Tree?在 Mobx-State-Tree 中声明全局操作的最佳方式是什么?
【发布时间】:2018-01-31 16:48:05
【问题描述】:

假设我在状态树的不同部分有一组动作,除了它们的逻辑应该修改根节点上的某些属性,例如,切换 loading 属性以指示 UI 应该全局更改进度指示器可见性。

const Contacts = types.model( 'Contacts', {
    items: types.array(types.string)
}).actions(self=>({
    show: flow(function* fetchData(){
        // somehow indicate start of the loading process
        self.items = yield fetch();
        // somehow indicate end of the loading process
    }) 
}));

const Store = types.model('AppStore', {
    loading: types.optional(types.boolean, false),
    contacts: Contacts
}).actions(self => ({
    toggle() {
        self.loading = !self.loading;
    }
}));

虽然我当然可以使用 getRoot,但这会给测试流程带来一定的不便,并降低整体设计的透明度。

可能使用惰性组合和导出实例以及模块中的模型声明可以做到,但这对我来说看起来更奇怪。

在 Mobx-State-Tree 中处理此类问题的建议方法是什么?

【问题讨论】:

    标签: mobx mobx-react mobx-state-tree


    【解决方案1】:

    我认为您可以在模型中使用 types.reference 和 types.late 来访问根操作。

    【讨论】:

    • 引用方法看起来是合法的,需要记住的一点是它应该是可选类型,并且应该在模型之间共享密钥。
    猜你喜欢
    • 2019-11-26
    • 2016-09-18
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-13
    • 1970-01-01
    • 2012-12-22
    相关资源
    最近更新 更多