首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当我设置observable时,mobx-react观察器不会触发

当我设置observable时,mobx-react观察器不会触发
EN

Stack Overflow用户
提问于 2020-10-15 04:32:44
回答 1查看 1.3K关注 0票数 3

我正在尝试使用mobx和typescript创建一个react应用程序。但它不起作用。

我希望计时器能计时。我看到事件发生并更新计数器。但是组件不是重新渲染的。我做错了什么?

代码语言:javascript
复制
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>
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-15 17:28:44

您使用的是MobX 6吗?

Decorator API与MobX 5相比有了一些变化,现在你需要在构造函数中使用makeObservable方法来实现与以前相同的功能:

代码语言:javascript
复制
import { observable, action, makeObservable } from "mobx";

export class TestStore {
    @observable timer = 0;

    constructor() {
      makeObservable(this);
    }

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

尽管有一些新东西可能会让您完全放弃装饰器,但makeAutoObservable

代码语言:javascript
复制
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

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64361090

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档