考虑以下示例与MobX 5.15.4:
class Store {
@observable.shallow items = [];
}
const store = new Store();
store.items = [5, 6, 7, 8, 9];
Array.prototype.push.apply(store.items, [10, 11, 12, 13, 14]);
Array.prototype.unshift.apply(store.items, [0, 1, 2, 3, 4]);
为可观察数组调用Array.prototype.unshift
对我不起作用(而Array.prototype.push
有效)。这是堆栈跟踪:
mobx.module.js:3390 Uncaught Error: [mobx.array] Index out of bounds, 14 is larger than 10
at Array.set (mobx.module.js:3390)
at Object.set (mobx.module.js:3058)
at Proxy.unshift (<anonymous>)
at Module../index.js (index.js:30)
at __webpack_require__ (bootstrap:89)
at Object.0 (index.js:6200)
at __webpack_require__ (bootstrap:89)
at checkDeferredModules (bootstrap:45)
at Array.webpackJsonpCallback [as push] (bootstrap:32)
at index.js:1
Array.prototype.splice
也不起作用:
Array.prototype.splice.apply(store.items, [0, 0].concat([0, 1, 2, 3, 4]));
是错误,还是我误会了?我想我应该使用可观察数组的原型来使其工作。我尝试了以下方法,但还是没有运气:
const observableArrayPrototype = store.items.__proto__;
observableArrayPrototype.unshift.apply(store.items, [0, 1, 2, 3, 4]);
对于getPrototypeOf作品
let items = mobx.observable([]);
items = items.concat([5, 6, 7, 8, 9]);
console.log(items);
items.push.apply(items, [10, 11, 12, 13, 14]);
console.log(items);
items.unshift.apply(items, [0, 1, 2, 3, 4]);
console.log(items);
let items1 = mobx.observable([]);
const observablePrototype = Object.getPrototypeOf(items1);
items1 = items1.concat([5, 6, 7, 8, 9]);
console.log(items1);
observablePrototype.push.apply(items1, [10, 11, 12, 13, 14]);
console.log(items1);
observablePrototype.unshift.apply(items1, [0, 1, 2, 3, 4]);
console.log(items1);
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mobx/5.15.4/mobx.umd.js"></script>
您可以使用点差运算符吗?您一定可以致电
store.items.push([10, 11, 12, 13, 14]);
完成。如果您有newItems
数组,请使用
store.items.push(...newItems);
否则,您需要循环。