mobx:观察基元数组

问题描述 投票:0回答:1

我是mobx的新手,正在研究文档。在阅读了有关observableautorun的信息后,我创建了一个小型测试平台来使用该功能。

According to the docs(强调我的意思:):

可观察的值可以是JS原语,引用,普通对象,类实例,数组和映射。

但是我无法观察到并自动运行以处理原始数组。

  • 对象数组:自动运行可以侦听数组及其条目上的更改。
  • 数字数组:自动运行不会对数组及其条目的更改做出反应
  • 数字数组,总和作为计算值:自动运行可以监听计算值的变化。

这是示例代码:

import { observable, autorun, computed } from "mobx"

// example 1, array of objects
// observes array directly, works
var todos = observable([{ t: "A" }, { t: "B" }])
autorun(() => { console.log(todos) });
todos.push({ t: 'C' }); //autorun triggers

// example 2, array of primitives
// observes computed value, works
var numbers = observable([1, 2, 3])
var sum = computed(() => numbers.reduce((a, b) => a + b, 0))
autorun(() => console.log(sum.get()))
numbers.push(4) //autorun triggers

// example 3, array of primites
// observes array directly, does not work
var numbers = observable([1, 2, 3]);
autorun(() => { console.log(numbers) });
numbers.push(4); //autorun does not trigger
javascript typescript mobx
1个回答
0
投票

就像@observer装饰器/函数一样,自动运行将仅观察执行提供的函数期间使用的数据。

实际上,我已经运行了您的代码,并且自动运行按预期运行。

// example 2, array of primitives
// observes computed value, works
const {
  observable,
  computed,
  autorun
} = mobx;

var numbers = observable([1, 2, 3]);
autorun(() => {
  console.log(numbers);
});
numbers.push(4); //autorun does not trigger
<script src="https://cdnjs.cloudflare.com/ajax/libs/mobx/5.15.4/mobx.umd.min.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.