【发布时间】:2020-06-09 11:01:25
【问题描述】:
我尝试将 observables 设置为类模型的映射,但由于某种原因,Mobx 没有检测到类模型是否发生了变化。我做了一些修改,发现 Mobx 只检测对数组、映射、对象和原语之一的可观察对象的更改。这是一个例子。
所以我在文档中读到 mobx 也支持类实例作为可观察对象。一定是我做错了什么。
我选择了对象类型,但有什么方法可以将类模型用作可观察对象,以便我可以在其中添加一些方法?
class Task {
@observable list = new Map();
@action addTask = (data, type) => {
// this works when i use this
task = type === TASKTYPE.ROUTINE ? {
...Some Data
} : {
...Some Data
};
// but not this
task = type === TASKTYPE.ROUTINE ? new Routine({
...Some Data
}) : new Todo({
...Some Data
});
this.list.set(task.id, task);
updateTask(this.list);
}
// Whenever i call these actions below in some component it mutates the list only on the action block
// but doesnt reflect the changes if i use the 2nd option above
@action deleteTask = (id) => {
this.list.delete(id);
updateTask(this.list);
}
@action addTime = (item, amount = 10) => {
const nItem = this.list.get(item.id);
nItem.timeSpent = nItem.timeSpent + amount;
this.list.set(item.id, nItem);
updateTask(this.list);
}
}
【问题讨论】:
-
你看到我的回答了吗?有帮助吗?
标签: reactjs mobx mobx-react