问题:我们正在使用redux来管理应用程序中的状态。这会导致渲染中出现问题。数组中的更改(f.e.remove)未由dom-repeater正确处理。发生的情况是数据和盖章模板混淆了。
我想找到一种方法来通知dom-repeat元素有关数组的更改。
<template is="dom-repeat" items="[[data.items]]">
<repeater-item config="[[item]]" on-change="_onChange"></repeater-item>
</template>我在我的聚合物应用程序中有不可变的状态,所以我不能使用聚合物数组突变方法。
here is a plnkr
我尝试了什么:
1) this.set('data', newState);
因此,如果我要删除数据数组中的第一项,‘dom- <repeater-item>’将删除最后一个模板重复,并重新分配数据,如下所示:
template-1 receives data 2,
template-2 receives data 3,
...2)在第二次尝试中,我正在尝试notifySplices:
var splices = Polymer.ArraySplice.calculateSplices(newState.items, this.data.items);
this.data = newState;
this.notifySplices('data.items', splices);结果是一样的
3)出于某种原因,下面的方法几乎是可行的。
var splices = Polymer.ArraySplice.calculateSplices(newState.items, this.data.items);
this.data.items = newState.items;
this.notifySplices('data.items', splices);这会导致正确的模板删除,但在这里我收到一个错误:
VM47184 polymer-mini.html:2046 Uncaught TypeError: Cannot read property 'length' of undefined如果使用不可变状态,通知“dom-repeat”的正确方式是什么?
发布于 2016-06-27 15:11:22
我已经能够避免选项3的错误;为新数组添加Polymer.Collection.get似乎可以防止在方法完成和dom-repeat呈现更改后发生的错误。
_remove(id) {
var newState = {
items: this.data.items.filter(item => item.id !== id)
};
// Polymer.Collection.get somehow prevents an exception _after_ notifySplices is called
Polymer.Collection.get(newState.items);
// Retro-actively calculate splices in Polymer fashion
var prev = (this.data.items || []);
var splices = Polymer.ArraySplice.calculateSplices(newState.items, prev);
// Change the data _without_ Polymer being aware of it (because it isn't a direct property of the element)
this.data.items = newState.items;
// Notify Polymer about the array changes so dom-repeat can re-use the correct templates
this.notifySplices('data.items', splices);
}将其付诸实践:http://plnkr.co/edit/fFGWfL?p=preview
我不知道为什么这阻止了异常,这更多的是一个偶然的发现。
但这似乎仍然是一个次优的解决方案,因为您必须将受影响的数组隐藏在包装器对象中。
https://stackoverflow.com/questions/37994019
复制相似问题