如何在 Mobx 中将多个商店合并为 Root Store 并在彼此的字段和功能中进行访问

How to combine multiple stores as Root Store in Mobx and get access of in each other's fields and functions

我不知道如何将两个存储合并到一个 RootStore 中(使用 Typescript)。 例如,我有 liveImageStore.ts (使用请求图像的方法,还包含最后 10 个图像的 url 数组)和 notificationStore.ts(set/clear 通知有一些逻辑可以在整个应用程序中进一步使用。并且 liveImageStore.ts 中的请求提供了一些错误(例如,在 http 连接出现问题的情况下)。我想打电话来自notificationStore.ts的函数(setNotification which push in store new notification)在第一个商店的请求方法中。但是如何转发和输入呢? 通知程序组件显示消息使用 notificationStore.

这就是我使用根存储模式的方式:

class RootStore {
  childStoreOne: ChildStoreOne
  childStoreTwo: ChildStoreTwo

  constructor() {
    this.childStoreOne = new ChildStoreOne(this)
    this.childStoreTwo = new ChildStoreTwo(this)
  }
}

class ChildStoreOne {
  root: RootStore
  constructor(root: RootStore) {
    this.root = root
  }
  methodOne() {}
}

class ChildStoreTwo {
  root: RootStore
  constructor(root: RootStore) {
    this.root = root
  }

  getSomethingFromStoreOne() {
    this.root.childStoreOne.methodOne()
  }
}

这是 React 部分:

// holds a reference to the store (singleton)
let store: RootStore

// create the context
const StoreContext = createContext<RootStore | undefined>(undefined);

// create the provider component
function RootStoreProvider({ children }: { children: ReactNode }) {
  //only create the store once ( store is a singleton)
  const root = store ?? new RootStore()

  return <StoreContext.Provider value={root}>{children}</StoreContext.Provider>
}

// create the hook
function useRootStore() {
  const context = useContext(StoreContext)
  if (context === undefined) {
    throw new Error("useRootStore must be used within RootStoreProvider")
  }

  return context
}

只要确保您不在构造函数中访问其他商店,因为初始化顺序,此时可能不会创建某些子商店。

我刚才写了一篇关于这个模式的文章 post: Mobx root store pattern with react hooks 您还会找到一个 link 到 Nextjs 的演示项目。