为什么我的跟踪阵列在 Ember Octane 中没有更新? [英] Why won't my tracked array update in 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
显示了添加了新对象的数组,并且跟踪了 fields
数组,但是当我单击按钮时没有任何变化.>
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
}];
}
}
如果您尝试将 tracked
与对象而不是数组一起使用,您有两个选择:
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屋!