React Mobx ContextProvider



你能解释给我为什么我需要包装我的应用程序在商店提供程序时使用mobx与React上下文。我的意思:

// Create Counter Store
class CounterStore {
constructor() {
makeAutoObservable(this)
this.num = 0
}
inc() { this.num++ }
}
// Create React Context with store
const StoreContext = React.createContext(new CounterStore())
// Create hook for usage context
const useStore = () => React.useContext(StoreContext)
// Create component
const Counter = observer(() => {
const counterStore = useStore()
return (
<>
<div>{counterStore.num}</div>
<button onClick={() => counterStore.inc()}>
inc num
</button>
</>
)
})
// Create App component
const App = () => {
return (
<Counter />
)
}

Ok,一切正常,我可以访问我的计数器组件中的商店。

但我仍然没有将我的应用程序包装到商店提供商中,如:

/// same code as above with little change
// Now create context with no value:
const StoreContext = React.createContext()
// And create Provider with store.
const StoreProvider = ({children}) => {
return <StoreContext.Provider value={new CounterStore()}>
{children}
</StoreContext.Provider>
}
Then wrap App component with provider:
render(
<StoreProvider>
<App />
</StoreProvider>,
document.getElementById("root")
);

这段代码也可以工作。但我不明白为什么我需要创建SroreProvider和包装我的应用程序,如果没有它一切正常

简短的回答:如果您有上下文的默认存储值,则不一定需要用Provider包装所有内容。一切都会很顺利,因为MobX为观察者组件创建了自己的订阅机制,允许它们重新渲染。(也值得阅读这个文档,以了解为什么你可能想要有上下文,如果你不使用MobX)

甚至,在这种情况下,您甚至可能根本不需要上下文。你可以只创建一个store的单例实例,然后直接导入到你需要的地方,而不用操心provider。

但是有时候你可能想要用有上下文的provider。例如用于服务器端呈现,或用于测试目的。想象一下你的inc方法调用了一些api。但是对于测试,你不希望这样做,当测试时,你可以用不同的商店替换你的商店:

const TestStoreProvider = ({children}) => {
// With provider you can different store there
return <StoreContext.Provider value={new CounterStoreForTests()}>
{children}
</StoreContext.Provider>
}

在这种情况下,你可以把Provider作为组件的依赖注入。

最新更新