如何将mobx6存储连接到react 15.8组件?“未捕获不变冲突,只能在函数组件“”的主体内调用挂钩

91zkwejq  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(198)

我正在尝试将mobx存储连接到我的react组件。
图书馆版本:

"mobx": "^6.3.2"
 "mobx-react": "^7.2.0"
 "react": "16.8.2"
 "react-dom": "16.8.2"

下面是最简单的示例代码:
a、 tsx

const root_store = new RootStore();

ReactDOM.render(
    <Provider root_store={root_store}>
        <IApp></IApp>
    </Provider>,
    document.getElementById('root'),
);

b、 tsx(适用于iapp组件)

interface Props {
    root_store?: RootStore;
}

class App extends React.Component<Props> {
    render(): any {    
        return (
            <div>
                 <IEventsEmbedSkin />
            </div>
        )
    }
}

export const IApp = inject(({root_store}:{root_store:RootStore}) => {
    console.log(root_store);
    return {
        root_store: root_store,
    };
})(observer(App))

c、 tsx(用于ieventsembedskin组件^^)

interface Props {
    root_store?: RootStore;
}

class EventsEmbedSkin extends React.Component<Props> {

    render(): JSX.Element {
        return (
            <div></div>
        );
    }
}

export const IEventsEmbedSkin = inject(({root_store}:{root_store:RootStore}) => {
    console.log(root_store);
    return {
        root_store: root_store,
    };
})(observer(EventsEmbedSkin));

如果我不渲染 IEventsEmbedSkin 文件b.tsx中的组件(从文件c.tsx导入),文件b中的一切工作正常,响应任何存储更新。当我渲染 IEventsEmbedSkin 组件(从文件c.tsx导入)我收到以下错误:
未捕获不变冲突:只能在函数组件的主体内部调用挂钩。
组件中发生了上述错误:
未捕获不变冲突:只能在函数组件的主体内部调用挂钩。
有人能帮我做些什么吗?
我不能改变我的看法。
我的商店是这样的:
rootstore.tsx

export class RootStore {
    context_store: ContextStore;
    recording_store: RecordingStore;

    constructor(props: Props) {

        this.context_store = new ContextStore({
            root_store: this,
        }); 

        this.recording_store = new RecordingStore({
            root_store: this,
        });
    }
}

contextstore.tsx:

export class ContextStore {
    root_store: RootStore;
    status: 'pending' | 'error' | 'done' | 'debug' = 'debug';

    constructor(props: Props) {
        this.root_store = props.root_store;    

        makeObservable(
            this,
            {
                status: observable,
                initialise: action,
            },
            {
                autoBind: true,
            },
        );
    }

    public async initialise(): Promise<void> {
        this.status = 'pending';
        try {
            const data = await this.api_store.get_config_and_instance_data();

            runInAction(() => {
                this.status = 'done';
            });
        } catch (e) {
            runInAction(() => {
                this.status = 'error';
            });
        }
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题