【问题标题】:Polymer 1.5 How to notify dom-repeat when using immutable data structurePolymer 1.5 使用不可变数据结构时如何通知 dom-repeat
【发布时间】:2016-06-23 14:07:08
【问题描述】:

问题:我们正在使用 redux 来管理应用中的状态。这会导致渲染出现问题。 dom-repeater 未正确处理数组中的更改(例如删除)。发生的情况是数据和标记模板混淆了。

我想找到一种方法来通知dom-repeat 元素有关数组更改。

<template is="dom-repeat" items="[[data.items]]">
    <repeater-item config="[[item]]" on-change="_onChange"></repeater-item>
</template>

我的 Polymer 应用程序中有不可变状态,因此我不能使用 Polymer 数组突变方法。

here is a plnkr

我尝试了什么:
1) this.set('data', newState);
因此,如果我删除我的数据数组 'dom-repeat' 中的第一项,将删除最后一个模板 &lt;repeater-item&gt; 并重新分配数据,如下所示:

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”的正确方法是什么?

【问题讨论】:

    标签: polymer polymer-1.0


    【解决方案1】:

    我已经能够防止选项 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

    我不知道为什么这会阻止异常,这更像是一个意外发现。

    但这似乎仍然是一个次优解决方案,因为您必须将受影响的数组隐藏在包装器对象中。

    【讨论】:

      猜你喜欢
      • 2016-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多