我正在迁移一个使用 MobX 提供程序/注入模式的 React Native 应用程序。我的新根组件如下所示:
export const ShellComponent = observer(() => {
const {isInitialized, navigationStore} = useStores();
if (!isInitialized) {
return (
<SplashPage />
);
} else {
return (
<StartPage />
);
}
});
目前为止,一切都好。一旦我的商店中的isInitalized
标志发生更改,组件就会重新渲染。
但是,我有很多遗留组件类,在那里我无法使用钩子。所以我的存储设置还包含一个返回原始根存储而不是 React 上下文的getRootStore()
函数:
// 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);
因此,在我的组件类中,我现在可以调用getRootStore
函数,并且一切正常。 但是:我也可以在功能组件中使用getRootStore
。因此,只需在第一个片段中与getRootStore
交换useStores
即可。这就引出了一个问题:我忽略了什么来证明 React 上下文的区别和开销是合理的?
使用singleton
或instance
模式时,您不能(或者至少会非常困难和黑客(进行服务器端渲染,因为您希望每次渲染都有新的store
。
此外,测试东西可能有点困难,因为你不能在没有依赖模拟的情况下切换根存储,但是通过Provider
和Context
,你可以使用依赖注入。
但总的来说,如果你没有SSR
(在RN中你肯定没有(或者没有这样的测试,需要存储来嘲笑,那么这种模式是完全可以的。