【问题标题】:Array splice is not observed by mobxmobx 观察不到数组拼接
【发布时间】:2020-01-09 16:08:01
【问题描述】:

我已经定义了一个从数组中删除项目的操作:

export default class myStore {

  @observable items = [];
  ...
  ...

  @action deleteItem = async (target) => {
    try {
      await backendService.deleteItem(target.id);
      runInAction(() => {
        const targetIndex = this.items.indexOf(target);
        this.items.splice(targetIndex, 1);
      });
    } catch (error) {
      ...
    }
  };

  ...
  ...
}

尽管我将组件设为observer,但在我触发其他一些操作(单击、重命名等)之前,它仍然不会更新我的列表,在这种情况下,我将能够看到该项目已被删除。

我错过了什么吗?

【问题讨论】:

  • console.log(targetIndex);在 const targetIndex = this.items.indexOf(target); 之后
  • @Jackkobec 它给了我正确的索引(例如 3)。如果我手动刷新它或执行一些其他操作,它会正确更新列表。这不是实时的(未观察到)

标签: javascript arrays react-native mobx mobx-react


【解决方案1】:

试试这个解决方案:

@action deleteItem = async (target) => {
    try {
      await backendService.deleteItem(target.id);
      runInAction(() => {
        this.items = this.items.filter(item === target);
      });
    } catch (error) {
      ...
    }
  };

【讨论】:

  • 谢谢@Jackkobec,它成功了!但我仍然想知道为什么它不适用于拼接?有任何想法吗?同样在性能方面,哪个更好?
  • Splice 修改原始数组。过滤器根据谓词过滤的原始创建新的。性能问题是在了解数据计数的情况下打开的。如果这是一个小数组,那也没什么区别。
  • 我的数组长度不应该超过 100。但是你知道有没有办法(在 mobx 中)让它与 splice 一起工作?拼接的运行时间是 O(1),而过滤器的运行时间是 O(n)
  • 算法复杂度不同。但这是一个有趣的数据大小。如果数组中的项目不重,那是有原因的。接下来尝试拼接:this.items = this.items.splice(this.items.indexOf(target), 1);或 this.items.splice(this.items.indexOf(target); return;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-19
相关资源
最近更新 更多