You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Microsoft FAST框架数组内部属性变更后DOM不重渲染问题求助

FAST框架嵌套数组DOM不自动更新的解决方案

问题核心原因

FAST的@observable装饰器默认仅追踪数组引用变化和对象直接属性的修改。对于你这种嵌套结构,myArray中的每个元素是对象,其itemTwo属性又是一个数组——这个嵌套数组默认不会被自动追踪,所以直接对itemTwo执行增删操作(如push/splice)时,框架无法感知到变化,也就不会触发DOM重渲染。

三种可行解决方案

方案1:定义接口并标记嵌套数组为可观察属性(推荐)

通过明确的TypeScript接口,给itemTwo添加@observable装饰器,让FAST自动追踪该嵌套数组的变化。

import { FASTElement, customElement, observable, html, repeat, when } from '@microsoft/fast-element';

// 定义嵌套项类型
interface NestedItem {
  keyOne: string;
  keyTwo: boolean;
}

// 定义外层数组元素的接口,标记itemTwo为可观察
interface MyArrayItem {
  itemOne: string;
  @observable itemTwo: NestedItem[];
}

@customElement('my-element')
export class MyElement extends FASTElement {
    @observable myArray: MyArrayItem[] = []; // 初始化空数组避免未定义问题

    changeItem(index: number) {
      if (!this.myArray[index]) return;
      
      // 示例:给itemTwo添加新元素,此时会自动触发DOM更新
      this.myArray[index].itemTwo.push({
        keyOne: '新增嵌套项',
        keyTwo: true
      });

      // 示例:删除itemTwo的第一个元素
      // this.myArray[index].itemTwo.splice(0, 1);
    }
}

方案2:手动触发属性变化通知

如果不想定义接口,可以在修改itemTwo后,手动调用Observable.notify告诉框架该属性发生了变化。

import { FASTElement, customElement, observable, html, repeat, Observable, when } from '@microsoft/fast-element';

@customElement('my-element')
export class MyElement extends FASTElement {
    @observable myArray: {itemOne: string, itemTwo: {keyOne: string, keyTwo: boolean}[]}[] = [];

    changeItem(index: number) {
      const targetItem = this.myArray[index];
      if (!targetItem) return;
      
      // 修改itemTwo数组
      targetItem.itemTwo.push({ keyOne: '手动通知新增项', keyTwo: false });
      
      // 通知框架:targetItem的itemTwo属性已变化
      Observable.notify(targetItem, 'itemTwo');
    }
}

方案3:手动定义可观察属性

在创建myArray元素时,使用Observable.defineProperty将itemTwo设置为可观察属性,后续修改时会自动触发更新。

import { FASTElement, customElement, observable, html, repeat, Observable, when } from '@microsoft/fast-element';

@customElement('my-element')
export class MyElement extends FASTElement {
    @observable myArray: {itemOne: string, itemTwo: {keyOne: string, keyTwo: boolean}[]}[] = [];

    // 示例:添加新元素到myArray
    addNewItem() {
      const newItem = {
        itemOne: '新外层元素',
        itemTwo: []
      };
      // 将itemTwo定义为可观察属性
      Observable.defineProperty(newItem, 'itemTwo', { value: [] });
      this.myArray.push(newItem);
    }

    changeItem(index: number) {
      const targetItem = this.myArray[index];
      if (!targetItem) return;
      
      // 此时修改itemTwo会自动触发DOM更新
      targetItem.itemTwo.splice(1, 0, { keyOne: '插入项', keyTwo: true });
    }
}

模板无需修改

你的现有模板已经正确绑定了itemTwo,只要嵌套数组的变化被FAST感知到,内层的repeat指令就会自动重渲染对应的DOM内容。

内容的提问来源于stack exchange,提问作者Alam Delta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 00:38:37