官术网_书友最值得收藏!

Observable arrays

Using observable.array() is very similar to using an observable(). You pass an array as initial value or start with an empty array. In the following code example, we are starting with an empty array:

const items = observable.array(); // Start with empty array

console.log(items.length); // Prints: 0

items
.push({
name: 'hats', quantity: 40,
});

// Add one in the front
items.unshift({ name: 'Ribbons', quantity: 2 });

// Add at the back
items.push({ name: 'balloons', quantity: 1 });

console.log(items.length); // Prints: 3

Do note that the observable array is not a real JavaScript array, even though it has the same API as a JS Array. When you are passing this array to other libraries or APIs, you can convert it into a JS Array by calling toJS(), as shown here:

import { observable, toJS } from 'mobx';

const
items = observable.array();

/* Add/remove items*/

const
plainArray = toJS(items);
console.log(plainArray);
MobX will apply  deep observability  to observable arrays, which means it will track additions and removals of items from the array and also track property changes happening to each item in the array.
主站蜘蛛池模板: 合山市| 保定市| 中西区| 铜川市| 连州市| 张北县| 涪陵区| 汾阳市| 泌阳县| 仁布县| 常州市| 白水县| 东光县| 随州市| 房山区| 涡阳县| 肥城市| 红河县| 永寿县| 陕西省| 太保市| 华宁县| 轮台县| 密山市| 嫩江县| 奉新县| 金湖县| 秦皇岛市| 柘荣县| 万载县| 喀喇| 广安市| 凭祥市| 万年县| 康平县| 藁城市| 曲阳县| 云南省| 澄城县| 柘城县| 涞源县|