Ilj*_*lja 6 javascript reactjs mobx mobx-react
假设以下结构
stores/
RouterStore.js
UserStore.js
index.js
Run Code Online (Sandbox Code Playgroud)
每个...Store.js文件都是一个包含@observable和的 mobx 存储类@action。index.js只导出所有商店,所以
import router from "./RouterStore";
import user from "./UserStore";
export default {
user,
router
};
Run Code Online (Sandbox Code Playgroud)
访问另一家商店的正确方法是什么?即在我的 UserStore 中,当用户身份验证更改时,我需要从 RouterStore 分派操作。
我累了import store from "./index"里面UserStore,然后用store.router.transitionTo("/dashboard")(transitionTo)是RouterStore的类内的动作。
但这似乎不能正常工作。
您提出的解决方案不起作用,因为您对包含观察值的商店实例而不是没有状态的 Store 类感兴趣。
鉴于您在商店依赖项之间没有任何循环,您可以将一个商店作为构造函数参数传递给另一个商店。
就像是:
routerStore = new RouterStore();
userStore = new UserStore(routerStore);
stores = {user: userStore, router: routerStore};
Run Code Online (Sandbox Code Playgroud)
在这里,您将 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.
}
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是在调用 userStore 中的函数时将其他存储(例如 routerStore)作为参数传递。
在这种情况下,您只需要传递一个链接
只需创建全球商店并将 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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6298 次 |
| 最近记录: |