mobx-react observer don't fires when I set observable

≡放荡痞女 提交于 2021-01-09 08:43:22

问题


I am trying to create a react application using mobx and typescript. But it doesn't work.

I expect the timer to count the seconds. And I see that the event happens and updates the counter. But the component is not rerender. What am I doing wrong?

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

回答1:


Are you using MobX 6?

Decorator API changed a little bit from MobX 5, now you need to use makeObservable method inside constructor to achieve same functionality as before:

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

export class TestStore {
    @observable timer = 0;

    constructor() {
      makeObservable(this);
    }

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

Although there is new thing that will probably allow you to drop decorators altogether, 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;
    };
}

More info here: https://mobx.js.org/react-integration.html



来源:https://stackoverflow.com/questions/64361090/mobx-react-observer-dont-fires-when-i-set-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!