在 MobX 中使用 React Context 的实际优势是什么?
What is the actual advantage of using React Context in MobX?
我正在迁移一个使用 MobX provider/inject 模式的 React Native 应用程序。我的新根组件看起来像这样:
export const ShellComponent = observer(() => {
const {isInitialized, navigationStore} = useStores();
if (!isInitialized) {
return (
<SplashPage />
);
} else {
return (
<StartPage />
);
}
});
到目前为止,还不错。一旦我商店中的 isInitalized
标志发生变化,组件就会重新呈现。
但是,我有很多遗留组件 class 在那里,我不能使用钩子。所以我的商店设置还包含一个 getRootStore()
函数,该函数 returns 原始根存储而不是 React 上下文:
// single root store instance
const rootStoreInstance: RootStore = new RootStore();
// expose the store
export const getRootStore = () => rootStoreInstance;
// Root store wrapped in a React context.
const rootStoreContext: React.Context<RootStore> = React.createContext<RootStore>(rootStoreInstance);
// Root store hook
export const useStores = () => React.useContext(rootStoreContext);
所以在我的组件 class 中,我现在可以调用 getRootStore
函数并且一切正常。
但是:我也可以在我的功能组件中使用 getRootStore
。因此,只需在第一个代码段中将 useStores
与 getRootStore
交换即可。这引出了一个问题:我忽略了什么来证明这里 React 上下文的区别和开销是合理的?
当使用 singleton
或 instance
模式时,你不能(或者至少它会非常困难和 hacky)有服务器端渲染,因为你需要为每个渲染新的 store
.
此外,测试东西可能有点困难,因为你不能在没有依赖模拟的情况下切换你的根存储,但是使用 Provider
和 Context
你可以使用依赖注入。
但总的来说,如果你没有 SSR
(在 RN 中你肯定没有)或者没有这样的测试,需要模拟存储,那么这个模式是完全可以的.
我正在迁移一个使用 MobX provider/inject 模式的 React Native 应用程序。我的新根组件看起来像这样:
export const ShellComponent = observer(() => {
const {isInitialized, navigationStore} = useStores();
if (!isInitialized) {
return (
<SplashPage />
);
} else {
return (
<StartPage />
);
}
});
到目前为止,还不错。一旦我商店中的 isInitalized
标志发生变化,组件就会重新呈现。
但是,我有很多遗留组件 class 在那里,我不能使用钩子。所以我的商店设置还包含一个 getRootStore()
函数,该函数 returns 原始根存储而不是 React 上下文:
// single root store instance
const rootStoreInstance: RootStore = new RootStore();
// expose the store
export const getRootStore = () => rootStoreInstance;
// Root store wrapped in a React context.
const rootStoreContext: React.Context<RootStore> = React.createContext<RootStore>(rootStoreInstance);
// Root store hook
export const useStores = () => React.useContext(rootStoreContext);
所以在我的组件 class 中,我现在可以调用 getRootStore
函数并且一切正常。
但是:我也可以在我的功能组件中使用 getRootStore
。因此,只需在第一个代码段中将 useStores
与 getRootStore
交换即可。这引出了一个问题:我忽略了什么来证明这里 React 上下文的区别和开销是合理的?
当使用 singleton
或 instance
模式时,你不能(或者至少它会非常困难和 hacky)有服务器端渲染,因为你需要为每个渲染新的 store
.
此外,测试东西可能有点困难,因为你不能在没有依赖模拟的情况下切换你的根存储,但是使用 Provider
和 Context
你可以使用依赖注入。
但总的来说,如果你没有 SSR
(在 RN 中你肯定没有)或者没有这样的测试,需要模拟存储,那么这个模式是完全可以的.