如何访问另一个 mobx 商店中的 mobx 商店? [英] How can I access mobx store in another mobx store?

查看:133
本文介绍了如何访问另一个 mobx 商店中的 mobx 商店?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设如下结构

stores/
  RouterStore.js
  UserStore.js
  index.js

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

each of ...Store.js files is a mobx store class containing @observable and @action. index.js just exports all stores, so

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

export default {
  user,
  router
};

进入另一家商店的正确方法是什么?即在我的 UserStore 中,当用户身份验证更改时,我需要从 RouterStore 分派操作.

What is correct way to access one store inside another? i.e. inside my UserStore, I need to dispatch action from RouterStore when users authentication changes.

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

I tired import store from "./index" inside UserStore and then using store.router.transitionTo("/dashboard") (transitionTo) is an action within RouterStore class.

但这似乎无法正常工作.

But this doesn't seem to work correctly.

推荐答案

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

Your propose solution doesn't work because you are interested in the instance of the store which contains the observed values instead of the Store class which has no state.

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

Given that you don't have any loop between store dependencies, you could pass one store as a constructor argument to another store.

类似于:

routerStore = new RouterStore(); 
userStore = new UserStore(routerStore); 

stores = {user: userStore, router: routerStore};

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

Here you pass the routerStore instance to the userStore, which means that it'll be available. For example:

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)作为参数传递.


Another way could be to pass the other store (say routerStore) as an argument when calling a function that is in userStore.

这篇关于如何访问另一个 mobx 商店中的 mobx 商店?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆