【问题标题】:ember.js list template keeps getting bigger on each visitember.js 列表模板在每次访问时都变得越来越大
【发布时间】:2018-03-01 06:30:58
【问题描述】:

总结

Ember 显示的列表有问题,每次访问时都会显示额外的行。额外的行与最初显示的行重复。

详情

在 Emberjs 2.13.0 应用程序中,我有一个看起来像这样的模型:

从“ember-data”导入 DS;

export default DS.Model.extend({
    cceIdentifierParent: DS.attr('string'),
    cchCceIdParent: DS.attr('string'),
    nodeType: DS.attr('number')
});

我有一条路线,“diagcctreetoplevelonly”,如下所示:

import Ember from 'ember';

export default Ember.Route.extend({
    model: function() {
        return this.store.findAll('diagcctreetoplevelonly');
  }
});

还有一个看起来像这样的模板:

{{diag-warningbanner}}
{{#if model.length}}
  <table>
    <thead>
      <tr>
        <th>
            cceIdentifierParent
        </th>
        <th>
            cchCceIdParent
        </th>
        <th>
            nodeType          
        </th>
      </tr>
    </thead>
    <tbody>
        {{#each model as |treenode|}}
           <tr>
              <td>
                {{treenode.cceIdentifierParent}}
              </td>
              <td>
                {{treenode.cchCceIdParent}}
              </td>
              <td>
                {{treenode.nodeType}}
              </td>
            </tr>
        {{/each}}
    </tbody>
  </table>
{{else}}
  <p id="blankslate">
    No Tree Nodes found
  </p>
{{/if}}
{{outlet}}

第一次访问“diagcctreetoplevelonly”时效果很好 - 呈现了 12 行 - 但在后续访问中(基础数据未更改),模板呈现的表格每次被访问时都有 12 额外的行.

谁能解释我做错了什么?谢谢。


编辑:感谢@Jeff 和@Subtletree 的输入,我能够解决这个问题。

问题是返回的数据没有“id”属性,当我创建一个时,问题就消失了。

由于数据的特殊性质,实际上 ID 是什么并不重要,而且我不想对后端进行更改,因此我在数据到达客户端后通过创建一个动态创建一个 ID模型级序列化程序并像这样覆盖extractId 方法:

import ApplicationSerializer from './application';

export default ApplicationSerializer.extend({
    extractId(modelClass, resourceHash) {
        var arrId = [];
        arrId.push(resourceHash['attributes']['cceIdentifierParent']);
        arrId.push(resourceHash['attributes']['cchCceIdParent']);
        arrId.push(resourceHash['attributes']['nodeType']);
        var id = arrId.join('|');
        return id == null || id === '' ? null : id+'';
  },
});

它不会在所有(也许大多数?)情况下都有效,但对我来说这已经足够好并且解决了问题。

为了提供应有的信用,我从@Casey 的答案https://stackoverflow.com/a/35738573/364088 中得到了如何做到这一点的想法。

【问题讨论】:

  • 这看起来绝对正确,所以我猜测有几个可能性:“额外”数据集是否与前 12 个相同? api 有效负载是否包含正确的 id? Ember 是否在每次访问时都请求数据?有效负载是什么样的?
  • 完全刷新时多余的行是否消失了?
  • @Jeff 感谢您的 cmets,他们是我解决问题的一部分。我即将编辑这个问题,以便为任何后续读者提供更多信息。再次感谢。

标签: ember.js handlebars.js


【解决方案1】:

ember-data 从服务器接收到记录时,它会尝试通过它们的 id 将它们与存储中的记录进行匹配。如果不存在 id,则找不到匹配项,因此不会更新它们,而是添加它们。

您可以为每条记录添加一个 id,或者可以使用 ajax 获取数据,而不是在此模型中使用 ember-data

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 2012-10-25
    • 2017-02-08
    • 2011-01-09
    • 2014-01-09
    • 2016-11-03
    • 2016-06-12
    相关资源
    最近更新 更多