React-Native Mobx 移除项目

waz*_*aze 3 javascript react-native mobx

如何从 Mobx observable 中的数组中删除项目?

这是可观察的:

@persist('list') @observable eventos = []
Run Code Online (Sandbox Code Playgroud)

这就是我向列表中添加项目的方式:

  @action addEvento (id, title) {
    this.eventos.push({
      id: id,
      nome: title,
    })
  }
Run Code Online (Sandbox Code Playgroud)

这就是我试图删除它的内容:

  @action removeEvento (id, title) {
    var i = this.eventos.indexOf(id);
    console.log(i)
    if(i != -1) {
      this.eventos.splice(i, 1)
      return this.eventos
    }
  }
Run Code Online (Sandbox Code Playgroud)

但它总是删除最后添加的项目,而不是我要删除的项目。此外,indexOf 始终返回 -1。

Tho*_*lle 5

您正在尝试使用 value 查找元素的索引id,但您想找到对象的id位置等于id

您可以例如使用过滤器并替换:

@action removeEvento (id, title) {
  var filteredEventos = this.eventos.filter(evento => evento.id !== id);
  this.eventos.replace(filteredEventos);
}
Run Code Online (Sandbox Code Playgroud)