mobx-observableを設定してもreactobserverが起動しない

Oct 14 2020

mobxとtypescriptを使用してreactアプリケーションを作成しようとしています。しかし、それは機能しません。

私はタイマーが秒を数えることを期待しています。そして、イベントが発生し、カウンターが更新されていることがわかります。ただし、コンポーネントは再レンダリングされません。私は何が間違っているのですか?

import React from "react";
import { observable, action } from "mobx";
import { observer, inject, Provider } from "mobx-react";

export class TestStore {
    @observable timer = 0;

    @action timerInc = () => {
        this.timer += 1;
    };
}

interface IPropsTestComp {
    TestStore?: TestStore;
}

@inject("TestStore")
@observer
export class TestComp extends React.Component<IPropsTestComp> {
    constructor(props: IPropsTestComp) {
        super(props);
        setInterval(() => {
            this.props.TestStore!.timerInc();
        }, 1000);
    }

    render() {
        return <div>{this.props.TestStore!.timer}</div>;
    }
}

export class TestApp extends React.Component {
    render() {
        return <Provider TestStore={new TestStore()}>
            <TestComp />
        </Provider>
    }
}

回答

3 Danila Oct 15 2020 at 09:28

MobX 6を使用していますか?

デコレータAPIはMobX5から少し変更さmakeObservableれました。以前と同じ機能を実現するには、コンストラクタ内のメソッドを使用する必要があります。

import { observable, action, makeObservable } from "mobx";

export class TestStore {
    @observable timer = 0;

    constructor() {
      makeObservable(this);
    }

    @action timerInc = () => {
        this.timer += 1;
    };
}

おそらくデコレータを完全に削除できる新しいものがありますが、makeAutoObservable:

import { makeAutoObservable } from "mobx";

export class TestStore {
    timer = 0;

    constructor() {
      // Don't need decorators now, just this call
      makeAutoObservable(this);
    }

    timerInc = () => {
        this.timer += 1;
    };
}

詳細はこちら:https://mobx.js.org/react-integration.html