问题描述
我正在使用 mobx/react 构建两个小部件,其中所有逻辑都位于商店内.两者共享大部分设计规则,因此它们的商店有 95% 相同.有没有聪明的方法来处理这种情况?例如,是否可以创建这样的继承?
class Animal {@observable 名称 = "";构造函数(名称){this.name = 名称;}@computed get 语句() {console.log(this.name + ' 发出噪音.');}}类狗扩展动物{@observable isBarking = false;@computed get bark() {如果(this.isBarking){console.log('狗在叫');}}@行动setIsBarking(isBarking) {this.isBarking = isBarking;}}
是的,你可以,但你必须像这样构建它,使用不使用装饰器的新 Mobx 模式:
(使用打字稿)
从mobx"导入{observable、action、computed、makeObservable};const 动物道具 = {名称:可观察,句子:计算};类抽象动物{名称 = ";构造函数(名称){this.name = 名称;}得到句子(){console.log(this.name + ' 发出噪音.');}}类狗扩展动物{isBarking = false;构造函数(){makeObservable(这个,{...动物道具,isBarking:可观察的,树皮:计算,setIsBarking: 动作});}得到树皮(){如果(this.isBarking){console.log('狗在叫');}}setIsBarking(isBarking) {this.isBarking = isBarking;}}如果您的应用中需要一个 Animal 实例,那么 Mobx-State-Tree 是更好的选择.因为让 prop observable/actionable/computable 两次(父类和子类)会抛出错误.
I'm building two widgets with mobx/react, where all the logic sits inside the stores. Both share most of the design rules, so their stores are 95% identical.Is there a smart way to handle this situation?For example, is it possible to create inheritance such as this?
class Animal {
@observable name = "";
constructor(name) {
this.name = name;
}
@computed get sentence() {
console.log(this.name + ' makes a noise.');
}
}
class Dog extends Animal {
@observable isBarking = false;
@computed get bark() {
if (this.isBarking){
console.log('The dog is barking');
}
}
@action
setIsBarking(isBarking) {
this.isBarking = isBarking;
}
}
Yes you can, but you have to structure it like this, using the new Mobx pattern which does not use decorators:
(Using Typescript)
import {observable, action, computed, makeObservable} from "mobx";
const animalProps = {
name: observable,
sentence: computed
};
class abstract Animal {
name = "";
constructor(name) {
this.name = name;
}
get sentence() {
console.log(this.name + ' makes a noise.');
}
}
class Dog extends Animal {
isBarking = false;
constructor(){
makeObservable(this, {
...animalProps,
isBarking: observable,
bark: computed,
setIsBarking: action
});
}
get bark() {
if (this.isBarking){
console.log('The dog is barking');
}
}
setIsBarking(isBarking) {
this.isBarking = isBarking;
}
}
If you need an instance of Animal in your app, then Mobx-State-Tree is a better option. Because making a prop observable/actionable/computable twice (the parent class and the subclass) will throw an error.
这篇关于是否可以在两个 mobx 商店之间创建继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!