【问题标题】:Dom-repeat not re-rendering when Array sorts数组排序时Dom-repeat不会重新渲染
【发布时间】:2019-03-02 22:34:08
【问题描述】:

我有一个数组属性:

arrayList: {
    type: Array,
    value:[
              {id:"1",candy:"Reeces"},
              {id:"1",candy:"M&M"},
              {id:"1",candy:"KitKat"},
              {id:"1",candy:"Twizzlers"}
          ]
}

和一个布尔属性

forceRerender: {
    type: Boolean,
    value: false
}

我在 Dom-Repeat 中调用它们来填充 HTML:

<template is="dom-repeat" as="candy" items="[[getCandyList(arrayList, forceRerender)]]">
    <div id="[[candy.id]]" class="candy-row" data="[[candy]]" on-tap="selectCandy">
</template>

selectCandy() 函数如下所示:

selectCandy(event) {
    let arr = this.arrayList;
    for(let j = 0, i = 0; j < arr.length; j++) {
        if(arr[j].select) {
            let temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            i++;
        }
    }
    this.set('forceRerender', !this.forceRerender);
}

还有我的吸气剂:

getCandyList(arr,forceRerender) {
    return arr;
}

我的selectCandy() 有效地重新排列了arrayList,但没有在视觉上更新HTML 内容来表示这一点。我似乎无法弄清楚为什么。

我制作了一个单独的数组并用它来更改值。我制作了一个本地数组并推送到该数组并返回它。我已经改写了事情的完成顺序。将各个部分分开多次以单独查看每个部分。

我在这玩了至少 3 个小时,我迷路了。谁能在这里向我解释我做错了什么?

【问题讨论】:

    标签: polymer-2.x


    【解决方案1】:

    下面这个例子可以给你一些启发。据我了解,您想向上(顶部)移动所选项目。

    Demo

    <template is="dom-repeat" items="[[getCandyList(arrayList, forceRerender)]]" as="candy">
        <paper-item on-tap="selectCandy"> <div id="[[candy.id]]" class="candy-row" data="[[candy]]"> [[candy.id]] - [[candy.candy]]</div>   
        </paper-item>
    </template>
    

    而 Js 可能看起来像:

    selectCandy(e) {
          let temp = this.arrayList;
          //In order to observable change in dom-repeat
          this.set('arrayList', []); 
          temp.splice(e.model.index, 1);
          temp.unshift(e.model.candy); 
          this.set("arrayList",  temp);
    
          this.set('forceRerender', !this.forceRerender);
    }
    

    您可以使用其他类型重新组织数组。

    【讨论】:

      【解决方案2】:

      我找到了解决办法:

      getCandyList(arr,forceRerender) {
          let rowList = [];
          for(let j = 0, i = 0; j < arr.length; j++) {
              if(arr[j].select) {
                  let temp = arr[i];
                  arr[i] = arr[j];
                  arr[j] = temp;
                  i++;
              }
          }
          arr.forEach(function(object) {
              rowList.push(object);
          }.bind(this));
          return rowList;
      }
      

      selectCandy(event) {
          this.set('forceRerender', !this.forceRerender);
      }
      

      这个故事的寓意是在 get 函数中对对象和数组做所有你想做的事情。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-31
        • 2021-10-21
        • 2021-07-29
        • 1970-01-01
        • 1970-01-01
        • 2020-02-13
        • 2021-12-03
        • 2018-11-18
        相关资源
        最近更新 更多