[英]how to use functional mobX store in react class components?
這是我的初始化存儲功能:
import React, { FC } from 'react';
import { useLocalObservable } from 'mobx-react';
import { TestStore, ITestStore } from './TestStore';
interface IStoreContext {
testStore: ITestStore;
}
export const StoreContext = React.createContext<IStoreContext>({} as IStoreContext);
export const StoreProvider: FC = ({ children }) => {
const testStore = useLocalObservable(TestStore);
const stores = {
testStore,
};
return <StoreContext.Provider value={stores}>{children}</StoreContext.Provider>;
};
export const useRootStore = () => {
const rootStore = React.useContext(StoreContext);
if (!rootStore) {
throw new Error('useStore must be used within a StoreProvider');
}
return rootStore;
};
這就是我使用它的方式:
const { testStore } = useRootStore();
但是我不能在類組件中使用鈎子。 那么如何在類組件中獲取 store 呢? 謝謝。
您可以創建一個使用您的鈎子並將結果傳遞給包裝類組件的高階組件。
例子
function withRootStore(Component) {
return function WrappedComponent(props) {
const rootStore = useRootStore();
return <Component {...props} rootStore={rootStore} />;
}
}
// ...
class MyComponent extends React.Component {
render() {
const { testStore } = this.props.rootStore;
// ...
}
}
export default withRootStore(MyComponent);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.