javascript - Mobx:Observable 数组显示不正确

标签 javascript arrays mobx

我想了解如何在 Mobx 中使用可观察数组。

我很难弄清楚这是为什么:

let entities = observable([]);
entities[0] = "foo";
autorun(() =>{
  console.log(entities);
});

写道:

[$mobx: Object]
0: (...)
1: (...)
2: (...)
3: (...)
4: (...)
5: (...)
6: (...)
7: (...)
8: (...)
9: (...)
10: (...)
11: (...)
12: (...)
13: (...)
14: (...)
15: (...)
16: (...)
17: (...)
...
999: (...)

而不是经典数组?

最佳答案

搞清楚!

如文档中所述

Bear in mind that Array.isArray(observable([])) will yield false, so whenever you need to pass an observable array to an external library, it is a good idea to create a shallow copy before passing it to other libraries or built-in functions (which is good practice anyway) by using array.slice() or array.peek(). So Array.isArray(observable([]).slice()) will yield true.

文档示例向我们展示了一个 todos.filter(),这可能会导致混淆,因为 todos 看起来像一个真正的 JS 数组。但事实并非如此。

因此,为了让我的示例正常工作,我只需要 console.log(entities.slice()) 即可显示真正的 JS 数组。

关于javascript - Mobx:Observable 数组显示不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35929369/

相关文章:

java - 声明两个 String 数组,一个在 Java 中扩展另一个数组

c++ - 数组、对象、类来组织具有多项选择和真/假问题的测试问卷程序

reactjs - React Stateless Function 组件出现 TypeScript 编译器错误

reactjs - React Hooks Mobx : invalid hook call. Hooks 只能在函数组件的主体内部调用

javascript - 无法使用 Socket.IO 向客户端广播

php - 使用 javascript 访问 php 文件中的 session 变量?

javascript - 如何调试 gulpfile.js

javascript - 将数组拆分成重叠的 block (移动子组)

reactjs - 无法在 bool 值 'true' 测试用例上准备属性 __mobxInstanceCount 失败 typescript 和 mobx

javascript - 从由 Array 组成的对象中获取值