gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:43:15 24 4
gpt4 key购买 nike

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

关于javascript - 如何在 Mobx 中将多个商店合并为 Root Store 并在彼此的字段和功能中进行访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67799148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com