No chance to make an strongly typed object observable by mobx

与世无争的帅哥 提交于 2019-12-11 00:38:43

问题


I use mobx library. It fit well with ReactJS. I have and observable array like this:

@observable items = [];

When I add an object in this way, I have no problem and the given object will be observable as expected.

let x = {
Title: "sample title"
}

items.push(x);

but when I define an strongly typed object (using typescript)

export class SampleObject {
    Title: string;
    constructor(title: string) {
        this.Title = title;
    }   
}

and pushing new object in this way, It won't be observable

items.push(new SampleObject("Sample Title"));

How can I solve this problem !?

What's the differences between x and y ?!

var x = {
Title: "sample"
}

var y = new SampleObject("sample");

回答1:


MobX only converts plain objects automatically to observable objects when assigning them to e.g. an array, because for class instances it might interfere with the internals of that class otherwise.

So in your class, just mark your fields (Title) as @observable as well and you should be good to go. See: https://mobxjs.github.io/mobx/refguide/object.html, second bullet



来源:https://stackoverflow.com/questions/39958358/no-chance-to-make-an-strongly-typed-object-observable-by-mobx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!