简体   繁体   English

如何在反应类组件中使用功能性 mobX 商店?

[英]how to use functional mobX store in react class components?

here is my init store function:这是我的初始化存储功能:

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;
};

and this is how i use it:这就是我使用它的方式:

const { testStore } = useRootStore();

But I can't use the hook inside the class component.但是我不能在类组件中使用钩子。 So how get the store inside the class component ?那么如何在类组件中获取 store 呢? thanks.谢谢。

You can create a Higher-Order Component that uses your hook and passes the result to the wrapped class component.您可以创建一个使用您的钩子并将结果传递给包装类组件的高阶组件

Example例子

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM