更改计算数组时 MobX 不更新 React 组件

MobX not updating React Component when computed array is changed

我在商店中有一份未排序的待办事项列表。添加一个计算值来存储 returns 排序的待办事项。 React 组件使用 sortedTodos 来显示列表。每当待办事项列表更改时,组件都不会重新呈现,如果我直接使用 todos 它会起作用。

export class TodoStore {
  @observable todos: Todo[] = [
    { description: "testing", createdAt: new Date(), isCompleted: false },
  ];

  @computed get sortedTodos(): Todo[] {
    const sortedTodos = this.todos.sort(
      (a, b) => a.createdAt.getTime() - b.createdAt.getTime()
    );
    return sortedTodos;
  }

  @action addTodo = (description: string) => {
    this.todos.push({
      description,
      createdAt: new Date(),
      isCompleted: false,
    });
  };
}

我找到了问题的解决方案。

我没有直接分配数组,而是使用了 observable.array 并且有效。

export class TodoStore {
  @observable todos: Todo[] = observable.array();

  ...
}

不完全确定为什么会这样,但它有效。我认为原因是通过使用常规数组,默认情况下内部对象不是可观察的,当使用 observable.array 时,数组的对象本身是可观察的。