如何在MobX的AccountStore中调用OtherStore的loadOthers方法?
在MobX的AccountStore中调用OtherStore的loadOthers方法的实现方式
方法一:构造函数注入(推荐,解耦性强)
通过在AccountStore的构造函数中传入OtherStore实例,明确依赖关系,便于维护和测试。
修改AccountStore代码:
export default class AccountStore { accounts : Account[] = []; private otherStore: OtherStore; constructor(otherStore: OtherStore) { makeAutoObservable(this); this.otherStore = otherStore; } loadAccounts = async () => { // 执行自身加载accounts的逻辑 // ... // 调用OtherStore的loadOthers方法 await this.otherStore.loadOthers(); } }
实例化Store时,先创建OtherStore再传入AccountStore:
const otherStore = new OtherStore(); const accountStore = new AccountStore(otherStore);
方法二:单例模式(适合全局唯一Store场景)
如果OtherStore是全局唯一实例,可以将其设计为单例,直接在AccountStore中调用。
修改OtherStore代码:
export default class OtherStore { others : Others[] = []; private static instance: OtherStore; // 私有构造函数防止外部直接实例化 private constructor() { makeAutoObservable(this); } // 获取单例实例 public static getInstance(): OtherStore { if (!OtherStore.instance) { OtherStore.instance = new OtherStore(); } return OtherStore.instance; } loadOthers = async () => { // 你的加载逻辑 } }
在AccountStore中调用:
export default class AccountStore { accounts : Account[] = []; constructor() { makeAutoObservable(this); } loadAccounts = async () => { // 执行自身加载accounts的逻辑 // ... // 调用单例的loadOthers方法 await OtherStore.getInstance().loadOthers(); } }
方法三:全局Store容器(适合小型项目)
将所有Store实例放在一个全局对象中,AccountStore直接引用该对象的OtherStore实例。
创建全局Store容器文件(比如stores.ts):
import AccountStore from './AccountStore'; import OtherStore from './OtherStore'; // 实例化所有Store const otherStore = new OtherStore(); const accountStore = new AccountStore(); // 导出全局Store容器 export const stores = { accountStore, otherStore };
修改AccountStore代码:
import { stores } from './stores'; export default class AccountStore { accounts : Account[] = []; constructor() { makeAutoObservable(this); } loadAccounts = async () => { // 执行自身加载accounts的逻辑 // ... // 调用全局容器中的OtherStore方法 await stores.otherStore.loadOthers(); } }
注:构造函数注入是最符合软件工程原则的方案,它能降低模块耦合,方便单元测试时替换依赖;单例和全局容器适合小型项目,但会增加模块间的耦合度。
内容的提问来源于stack exchange,提问作者Shury
相关产品推荐
相关产品推荐

