Mobx:Observable 数组显示不正确
Mobx: Observable array does not display correctly
我正在尝试了解如何在 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 数组。
另一种记录 mobx observable 的方法是使用 toJS
方法
import { toJS } from 'mobx';
class Store {
@observable
fruits = ['Apple', 'Banana'];
constructor() {
console.log('this.views :', toJS(this.data));
}
}
export default new Store();
希望对您有所帮助。 Source
我正在尝试了解如何在 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 数组。
另一种记录 mobx observable 的方法是使用 toJS
方法
import { toJS } from 'mobx';
class Store {
@observable
fruits = ['Apple', 'Banana'];
constructor() {
console.log('this.views :', toJS(this.data));
}
}
export default new Store();
希望对您有所帮助。 Source