如何在使用 React.createContext 创建的 Mobx 商店之间进行通信

How to communicate between Mobx stores created with React.createContext

我有我的 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 商店,并将其自身传递给子商店,这样它们就可以 "go up" 到 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 商店传递给 RootStore 构造函数中的 root 商店。

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());