Array.splice 后重置 MobX observable

Resetting MobX observable after Array.splice

我正在尝试使用 Array.splice 从索引处的数组中删除一个元素。这个数组在 MobX 存储中是可见的。我知道我不能在 MobX 数组上使用 splice,因为那样只会 return 它回到标准数组,并且不再可观察。

我需要使用索引来删除项目,因为可能存在具有重复值的项目,因此使用此处的过滤器解决方法将不起作用:

所以我想做的是使用 splice 修改数组,然后 重新观察 animalList 属性,但是这给出了Cannot convert 'LivestockStore@1.animalList' into observable object: The target is already observable of different type. 错误。

'''

export default class LivestockStore {

    animalList:Animal[] = new Array<Animal>();

    constructor() {
        makeAutoObservable(this);
    }

    removeAnimal = (index: number) => {
        const animalListModified = this.animalList;
        animalListModified.splice(index, 1);
        this.animalList = makeObservable(animalListModified);
    }
}

我无法将 index 存储在动物对象中,因为每次删除一个,我都必须重新计算所有 Index 值。我唯一的其他选择是使用 Map 并将 Guid 存储为每个元素的 key 并从中删除,但这似乎是修复一些应该相对简单的东西的 hack。

干杯, 贾斯汀

I know that I cannot use splice on a MobX array as that will just return it back to a standard Array, and no longer observable.

你绝对可以在这里使用 splice(并且应该,MobX 中的突变是正确的方法),它是什么数组并不重要 returns 因为你根本不需要那个部分在你的情况下。 (它 returns 删除了元素)

Codesandbox example

因此只需使用 splice,无需任何额外代码:

  removeAnimal = (index) => {
    this.animalList.splice(index, 1);
  };