我有我的useStores.ts文件,该文件具有两个按以下方式初始化的Mobx存储。
import StoreA from "./stores/StoreA";
import StoreB from "./stores/StoreB";
const storesContext = createContext({
storeA: new StoreA(),
storeB: new StoreB(),
});
export const useStores = () => useContext(storesContext);
因此,我可以通过以下方式在任何组件内部使用这些存储。
const { storeA } = useStores();
但是我不确定如何访问storeB内的storeA。
有人可以帮我吗?
您应该创建一个包含所有其他商店的root
商店,并将其自身传递给子商店,以便它们可以“上升”到root
商店,然后再到达任何其他商店。
class RootStore {
storeA = new StoreA(this)
storeB = new StoreB(this)
}
class StoreA{
constructor(rootStore){
this.rootStore = rootStore
// get to store B
// this.rootStore.storeB
}
}
与createContext
一起使用
const storesContext = createContext(new RootStore());
甚至更好,跟随dependency injection principles并将child
存储传递给root
构造函数中的RootStore
存储。
class RootStore {
constructor(a,b){
this.storeA = a
this.storeB = b
this.storeA.setRoot(this)
this.storeB.setRoot(this)
}
const storesContext = createContext(new RootStore(new StoreA(),new StoreB());