Mobx使用类模型定义可观察对象

问题描述 投票:0回答:1

我曾尝试将可观察对象设置为类模型的映射,但是由于某些原因,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
1个回答
0
投票

因此,您需要使Task.list容器以及容器内RoutineTodo实例的每个相关原语都可观察。我不使用装饰器,因此您必须检查语法是否正常。

class Task {
    @observable list = new Map();
    @action addTask = (data, type) => {

        task = type === TASKTYPE.ROUTINE ? new Routine({
            id: "someId"
        }) : new Todo({
            id: "someOtherId",
            settings: {}
        });

        this.list.set(task.id, task);
        updateTask(this.list);
    }
}
class Routine {
    constructor(options) {
        //each primitive inside the class can be observed
        @observable this.id = options.id;
    }
}
class Todo {
    constructor(options) {
        @observable this.id = options.id;
        //you can also observe changes to objects
       @observable this.settings = options.settings;
    }
}

希望有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.