基本使用
doc
https://www.mobxjs.com/#%E4%B8%80%E4%B8%AA%E7%AE%80%E5%8D%95%E7%9A%84%E4%BE%8B%E5%AD%90
import { makeAutoObservable } from "mobx";
import { observer } from "mobx-react";
// 对应用状态进行建模。
class Timer {
// 自动实现了旧版本的 @observable
secondsPassed = 0;
constructor() {
makeAutoObservable(this);
}
// 自动实现了旧版本的 @action
increase() {
this.secondsPassed += 1;
}
reset() {
this.secondsPassed = 0;
}
}
const myTimer = new Timer();
// 每秒更新一次‘已过秒数:X’中的文本。
setInterval(() => {
myTimer.increase();
}, 1000);
// 构建一个使用 observable 状态的“用户界面”。
const TimerView = observer(({ timer }: any) => (
<button onClick={() => timer.reset()}>已过秒数:{timer.secondsPassed}</button>
));
const App = () => <TimerView timer={myTimer} />;
export default App;
继承模板
import { useEffect } from "react";
import {
observable,
computed,
action,
override,
configure,
makeObservable,
} from "mobx";
configure({ enforceActions: "always" });
class Parent {
// Annotated instance fields are NOT overridable
observable = 200;
arrowAction = () => {};
extraFilterParams: any = {};
// Non-annotated instance fields are overridable
overridableArrowAction = action(() => {});
// Annotated prototype methods/getters are overridable
action() {}
actionBound() {}
get computed() {
return "computed";
}
constructor() {
makeObservable(this, { // makeAutoObservable 不能再继承中使用,makeObservable手动设置为可观察数据
observable: observable,
arrowAction: action,
action: action,
actionBound: action.bound,
computed: computed,
});
}
}
class Child extends Parent {
/* --- 继承来的定义 --- */
// 抛出 - TypeError: Cannot redefine property, field不能被继承
// observable = 5;
// arrowAction = () = {}
// OK - not annotated
overridableArrowAction = action(() => {});
// OK - prototype
actionBound() {}
get computed() {
return "heihei";
}
/* --- 新的定义 --- */
childObservable = 300;
childArrowAction = () => {};
childAction() {}
childActionBound() {}
get childComputed() {
return "child computed";
}
constructor() {
super();
makeObservable(this, {
// 继承来的
action: override,
actionBound: override,
computed: override,
// 新的
childObservable: observable,
childArrowAction: action,
childAction: action,
childActionBound: action.bound,
childComputed: computed,
});
}
}
const App = () => {
useEffect(() => {
const mParent = new Parent();
console.log("mParent: ", mParent);
const mChild = new Child();
console.log("mChild: ", mChild);
}, []);
return <div></div>;
};
export default App;
doc
https://www.mobxjs.com/subclassing
对使用子类的支持是有限制的。 最值得注意的一点是你只能重新定义原型中的 actions/flows/computeds——你不能重新定义字段声明。 在子类中请使用 override 注释被重新定义的methods/getters - 见下例。 请凡事从简,并优先考虑组合(而非继承)。