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

标签 reactjs typescript ecmascript-6 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

关于reactjs - 当我设置 observable 时,mobx-react 观察者不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64361090/

相关文章:

javascript - 修复生产 react 路由时,fetch 找不到 api url

ios - React native 错误 AppRegistry 未定义?

Node.js 在同一项目中进行 React 和 Rest 路由

javascript - 在reactjs中获取下拉列表的键值

typescript - 我怎样才能在 ionic 3 中转换 base64 数据中的 pdf、xlsx 和 doc 文件?

typescript - [嵌套接口(interface)/类型] : How to declare function return types inside a class in Typescript?

javascript - 失败 : invalid element state on attempt to . sendKeys() 到文本字段

javascript - Microsoft EDGE 消息 : SCRIPT1006: Expected ')'

javascript - react : Perform different operation depending on select option dropdown

javascript - 查找并获取与值匹配的对象数组(ES6)