微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Mobx 中将多个 store 组合为 Root Store 并在彼此的字段和函数中访问

如何解决如何在 Mobx 中将多个 store 组合为 Root Store 并在彼此的字段和函数中访问

我不知道如何将两个商店合并到一个 RootStore 中(使用 Typescript)。 例如,我有 liveImageStore.ts(使用请求图像的方法,还保存最后 10 个图像的 url 数组)和 notificationStore.ts(有一些逻辑要设置/清晰的通知,以便在整个应用程序中进一步使用。并且 liveImageStore.ts 中的请求提供了一些错误(例如,在 http 连接问题的情况下)。我想从 notificationStore.ts 调用函数(setNotification在第一个商店的请求方法中推送商店新通知)。但是如何转发和输入所有内容? Notifier 组件显示消息使用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
}

只要确保您没有访问构造函数中的其他存储,因为初始化顺序可能不会在那时创建某些子存储。

我不久前写了一篇关于这种模式的帖子: Mobx root store pattern with react hooks 您还可以找到 Nextjs 演示项目的链接。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。