从原型调用时,unshift&splice不适用于可观察到的数组

问题描述 投票:0回答:2

考虑以下示例与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]);
javascript mobx
2个回答
0
投票

对于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>

0
投票

您可以使用点差运算符吗?您一定可以致电

store.items.push([10, 11, 12, 13, 14]);

完成。如果您有newItems数组,请使用

store.items.push(...newItems);

否则,您需要循环。

© www.soinside.com 2019 - 2024. All rights reserved.