微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当我设置可观察者时,mobx反应观察者不会触发

如何解决当我设置可观察者时,mobx反应观察者不会触发

我正在尝试使用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>
    }
}

解决方法

您正在使用MobX 6吗?

Decorator API与MobX 5相比有所变化,现在您需要在构造函数中使用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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。