为什么我的跟踪阵列在Ember Octane中不更新? [英] Why won't my tracked array update in Ember Octane?

查看:96
本文介绍了为什么我的跟踪阵列在Ember Octane中不更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Octane,由于某种原因,如果我在模板中显示数组并向其中添加新对象,则UI不会更新。我在做什么错了?

I'm trying out Octane, and for some reason, if I show an array in a template and I add a new object to it, the UI doesn't update. What am I doing wrong?

这是我的模板:

<label for="new-field-name">Field Name</label>
<Input id="new-field-name" @value={{this.newFieldName}} type="text" />
<button {{on "click" this.addField}}>Add field</button>

{{#each this.fields as |field|}}
    <p>{{field.name}}</p>
{{/each}}

和组件:

import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';

export default class ConfigControlsComponent extends Component {
    @tracked fields = []
    @tracked newFieldName = ''

    @action addField() {
        this.fields.push({
            name: this.newFieldName
        })
        console.log(this.fields)
    }
}

console.log 显示带有新对象的数组添加到其中,并跟踪字段数组,但是单击按钮时没有任何变化。

The console.log shows the array with the new object added to it, and the fields array is tracked, but nothing changes when I click the button.

推荐答案

对数组使用 tracked 时,需要重置数组,以便Ember注意到发生了变化。将新对象推入数组后,尝试执行 this.fields = this.fields

When you use tracked with arrays, you need to "reset" the array so that Ember notices that there has been a change. Try doing this.fields = this.fields after pushing a new object into the array.

编辑:一些短毛猫会防备自我分配。因此,相反,我们可以从不变性模式中提取并使用新数组进行设置,如下所示。

some linters will guard against self-assignment. So, instead, we could pull from immutability patterns, and set using a new array, as shown below.

export default class ConfigControlsComponent extends Component {
  @tracked fields = []
  @tracked newFieldName = ''

  @action addField() { 
    // add this line
    this.fields = [...this.fields, {
      name: this.newFieldName
    }]; 
  }
}

如果您尝试使用使用对象而不是数组进行跟踪,您有两个选择:

If you are trying to use tracked with an object instead of an array, you have two options:

首先,您可以创建一个类,其中所有属性跟踪对象:

First, you could create a class where all the properties on the object are tracked:

import { tracked } from '@glimmer/tracking';

class Address {
  @tracked street;
  @tracked city;
}

class Person {
  address = new Address();

  get fullAddress() {
    let { street, city } = this.address;

    return `${street}, ${city}`;
  }
}

或者,第二,您可以使用相同的重置作为上面的数组示例。

Or, second, you could use the same "reset" approach as the array example above.

这篇关于为什么我的跟踪阵列在Ember Octane中不更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆