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

问题描述 投票:1回答:1

我有我的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。

有人可以帮我吗?

reactjs react-hooks mobx react-context mobx-react
1个回答
2
投票

您应该创建一个包含所有其他商店的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());
© www.soinside.com 2019 - 2024. All rights reserved.