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

  • MobX Quick Start Guide
  • Pavan Podila Michel Weststrate
  • 184字
  • 2021-08-05 10:34:23

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.
主站蜘蛛池模板: 绥宁县| 甘南县| 高阳县| 讷河市| 北流市| 德清县| 林周县| 漳州市| 元阳县| 永吉县| 永德县| 布尔津县| 鲁甸县| 法库县| 嫩江县| 东台市| 玉山县| 咸宁市| 曲靖市| 纳雍县| 武强县| 宜川县| 长阳| 阿鲁科尔沁旗| 揭东县| 马山县| 句容市| 微山县| 衢州市| 乌拉特后旗| 兴化市| 棋牌| 孟连| 临潭县| 射洪县| 绿春县| 秭归县| 即墨市| 夹江县| 哈密市| 永平县|