mobx 挑战:将 getter 和 setter 放入一个可观察的数组

问题描述

我正在尝试将 getter 和 setter 写入一个可观察的数组,但它不起作用。下面的代码给了我以下错误Error: [MobX] No annotations were passed to makeObservable,but no decorator members have been found either

我尝试了不同的装饰器组合,但似乎没有任何效果。我想要的行为是每当 AppModel.text 更新时,任何渲染文本获取器的 UI 都应该更新。此外,每当在对象上调用 gonext() 时,从 AppModel.text 渲染的任何 UI 都应更新并渲染来自数组上新 0 项的数据。

class DataThing
{
    @observable text?: string = "foo";
}

class AppModel
{
    get text() { return this.items[0].text}
    set text(value: string | undefined) { this.items[0].text = value;}

    items: DataThing[] = observable( new Array<DataThing>());

    constructor() { 
        makeObservable(this);  
        this.items.push(new DataThing());
    }

    gonext() { this.items.unshift(new DataThing()); }
}

编辑:

我最终做了以下事情,但仍然想了解如何以可观察的方式索引数组。

class DataThing
{
    @observable text?: string = "zorp";
    constructor(){makeObservable(this);}
}

class AppModel
{
    @observable _current?:DataThing;
    get current() {return this._current;}

    items: DataThing[] = observable( new Array<DataThing>());

    constructor() { 
        makeObservable(this);  
        this.gonext();
    }

    gonext() { 
        this.items.unshift(new DataThing()); 
        this._current = this.items[0];
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)