问题描述
我正在尝试遵循文档中的guide。这是我的组件:
脚
import { observer } from 'mobx-react-lite';
import React from 'react';
import Footerviewmodel from './footerviewmodel';
const viewmodel = new Footerviewmodel();
const Footer = observer(() => {
return (
<footer>
{viewmodel.content}
<button onClick={viewmodel.onClick}>Button</button>
</footer>
);
});
export default Footer;
Footerviewmodel
import { action,observable } from 'mobx';
export default class Footerviewmodel {
@observable
public content = 'asdasdasd';
@action
public onClick = (): void => {
this.content = '234';
console.log(this.content);
};
}
字段content
是可观察的,onClick
是 action ,而Footer
是observer
,应该。但是单击按钮不会调用组件的重新渲染。因此,content
字段正在更改。
我在做什么错了?
解决方法
根据文档,您需要致电makeAutoObservable:
import { action,makeAutoObservable} from 'mobx';
和
constructor() {
makeAutoObservable(this)
}
https://stackblitz.com/edit/mobx-5pjrm9?file=index.js
使用可观察的装饰器:
https://stackblitz.com/edit/mobx-react-lite-jrzgzf?file=index.js
,如果正在使用v6
(并且应该使用),则需要显式启用装饰器。
由于您在tsconfig.json
中使用TypeScript,因此需要启用以下编译器选项:
experimentalDecorators : true
和
useDefineForClassFields : true