【问题标题】:How can I access mobx store in another mobx store?如何在另一个 mobx 商店访问 mobx 商店?
【发布时间】:2017-07-05 14:12:04
【问题描述】:

假设以下结构

stores/
  RouterStore.js
  UserStore.js
  index.js

每个...Store.js 文件都是一个包含@observable@action 的mobx 存储类。 index.js 只是导出所有店铺,所以

import router from "./RouterStore";
import user from "./UserStore";

export default {
  user,
  router
};

在另一个商店中访问一个商店的正确方法是什么?即在我的 UserStore 中,当用户身份验证更改时,我需要从 RouterStore 调度操作。

我在 UserStore 中厌倦了 import store from "./index",然后使用 store.router.transitionTo("/dashboard") (transitionTo) 是 RouterStore 类中的一个动作。

但这似乎无法正常工作。

【问题讨论】:

    标签: javascript reactjs mobx mobx-react


    【解决方案1】:

    在这种情况下,您只需要传递一个链接

    只需创建全局商店并将 GlobalStore 的链接传递给您需要访问的每个子商店:

    // global parent store
    class GlobalStore {
        constructor() {
            this.routerStore = new RouterStore(this);
            this.userStore = new UserStore(this);
            // ... another stores
        }
    }
    
    // access in child
    class UserStore {
        constructor(rootStore) {
            this.routerStore = rootStore.routerStore;
        }
    
        // ...
    }
    
    // In root component:
    <MobxProvider {...new GlobalStore()}>
      <App />
    </MobxProvider>
    

    【讨论】:

    • 如何只为UserStore编写单元测试用例?
    • @ksh 模拟 rootStore 如果你在 UserStore 中使用它const userStore = new UserStore({...mockedData })
    【解决方案2】:

    您提出的解决方案不起作用,因为您对包含观察值的商店实例感兴趣,而不是没有状态的 Store 类。

    鉴于您在存储依赖项之间没有任何循环,您可以将一个存储作为构造函数参数传递给另一个存储。

    类似:

    routerStore = new RouterStore(); 
    userStore = new UserStore(routerStore); 
    
    stores = {user: userStore, router: routerStore};
    

    在这里,您将 routerStore 实例传递给 userStore,这意味着它将可用。例如:

    class UserStore {
        routerStore; 
        constructor(router) {
            this.routerStore = router
        }; 
    
        handleLoggedIn = () => {
             this.routerStore.transitionTo("/dashboard") 
             // Here the router has an observable/actions/... set up when it's initialized. So we just call the action and it all works. 
        }
    } 
    

    另一种方法是在调用 userStore 中的函数时将另一个存储(例如 routerStore)作为参数传递。

    【讨论】:

    • 嗯,有道理,首先应该是userStore = new UserStore(routerStore) 吗?其次,在 UserStore 类中,我只是在普通构造函数中接收路由器,还是需要对其应用一些 mobx 的东西,即使该存储成为观察者或其他东西?您有机会提供扩展示例吗?
    • 我修正了错字。感谢您的关注。
    • 您可以将 UserStore 用作普通的构造函数参数。您只需共享商店的实例,无需创建新商店,因此无需指定任何内容。我去找个例子
    猜你喜欢
    • 1970-01-01
    • 2021-11-21
    • 2018-06-11
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2021-02-10
    相关资源
    最近更新 更多