Sky*_*kyN 3 typescript ecmascript-6 reactjs mobx
我正在尝试使用 mobx 和 typescript 创建一个反应应用程序。但它不起作用。
我希望计时器可以计算秒数。我看到事件发生并更新了计数器。但该组件不会重新渲染。我究竟做错了什么?
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>
}
}
Run Code Online (Sandbox Code Playgroud)
你在使用 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;
};
}
Run Code Online (Sandbox Code Playgroud)
虽然有一些新东西可能会让你完全放弃装饰器,但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;
};
}
Run Code Online (Sandbox Code Playgroud)
更多信息在这里:https : //mobx.js.org/react-integration.html
| 归档时间: |
|
| 查看次数: |
1090 次 |
| 最近记录: |