Reactjs 如何在使用React.createContext创建的Mobx存储之间通信
我有一个useStores.ts文件,它有两个Mobx存储,初始化方式如下Reactjs 如何在使用React.createContext创建的Mobx存储之间通信,reactjs,react-hooks,mobx,react-context,mobx-react,Reactjs,React Hooks,Mobx,React Context,Mobx React,我有一个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 = () =>
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();
因此,我可以按照以下方式在任何组件中使用这些存储
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
存储,然后再到任何其他存储
类根存储{
storeA=新storeA(本)
storeB=新storeB(本)
}
StoreA类{
构造函数(rootStore){
this.rootStore=rootStore
//去B店
//this.rootStore.storeB
}
}
与createContext一起使用
const-storesContext=createContext(new-RootStore());
或者更好的方法是,在RootStore
构造函数中,遵循并将child
存储传递到root
存储
类根存储{
建造师(a、b){
this.storeA=a
this.storeB=b
this.storeA.setRoot(this)
this.storeB.setRoot(this)
}
const-storesContext=createContext(新的根存储(new-StoreA(),new-StoreB());
您应该创建一个包含所有其他存储的根存储,它将自身传递给子存储,这样子存储就可以“上”到根存储,然后再到任何其他存储
类根存储{
storeA=新storeA(本)
storeB=新storeB(本)
}
StoreA类{
构造函数(rootStore){
this.rootStore=rootStore
//去B店
//this.rootStore.storeB
}
}
与createContext一起使用
const-storesContext=createContext(new-RootStore());
或者更好的方法是,在RootStore
构造函数中,遵循并将child
存储传递到root
存储
类根存储{
建造师(a、b){
this.storeA=a
this.storeB=b
this.storeA.setRoot(this)
this.storeB.setRoot(this)
}
const-storesContext=createContext(新的根存储(new-StoreA(),new-StoreB());
你能告诉我如何使用createContext实现同样的功能吗?你能告诉我如何使用createContext实现同样的功能吗。