鸿蒙sdk5.1

错误代码,无法响应

interface shuju {
  status:string
  price:number
}

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  textstatus(item: shuju): string {
    switch (item.status) {
      case 'nn':
        return 'niaho'
        break;
      case 'nj':
        return 'niji'
        break;
      default:
        return '垃圾'
        break;
    }
  }
  @State lizi:shuju[]=[
    {status:'nj',price:11},
    {status:'nj',price:111},
    {status:'nj',price:12}
  ]

  xiugai(item:shuju){
    item.status='nn'
    console.log("items",item.price+item.status)

    console.log("lizi",JSON.stringify(this.lizi))
  }
  build() {

    Column() {
      ForEach(this.lizi,(item:shuju)=>{
        Text(`按钮显示${this.textstatus(item)}`)

        Button(`修改按钮显示框`)
          .onClick(()=>{
            this.xiugai(item)
          })

      })
    }
    .height('100%')
    .width('100%')
  }
}

可以深层响应的代码

// DeepMapResponse.ets
import { prompt } from '@kit.ArkUI';

/* ========== 深层可观察模型 ========== */
@ObservedV2
class Dish {
  @Trace id: number = 0
  @Trace name: string = ''
  @Trace status: string = 'COOKING'   // 深层字段变动会被跟踪
}

@ObservedV2
class Order {
  @Trace id: number = 0
  @Trace dishList: Dish[] = []
}

/* ========== 页面 ========== */
@Entry
@Component
struct DeepMapResponse {
  /* 顶层状态:数组里每个元素都是 @ObservedV2 实例 */
  @State orders: Order[] = this.initData()

  /* 初始数据:手写即可,无需展开 */
  private initData(): Order[] {
    const o1 = new Order()
    o1.id = 1
    const d1 = new Dish(); d1.id = 11; d1.name = '宫保鸡丁'
    const d2 = new Dish(); d2.id = 12; d2.name = '麻婆豆腐'
    o1.dishList = [d1, d2]

    const o2 = new Order()
    o2.id = 2
    const d3 = new Dish(); d3.id = 21; d3.name = '酸菜鱼'
    o2.dishList = [d3]
    return [o1, o2]
  }

  /* 中文文案 */
  private dishText(d: Dish): string {
    switch (d.status) {
      case 'COOKING': return '正在烹饪'
      case 'DONE': return '已完成'
      default: return '未知'
    }
  }

  private dishColor(d: Dish): ResourceColor {
    return d.status === 'DONE' ? '#00C853' : '#FFA500'
  }

  /* 完成一道菜:只改深层字段,UI 立即刷新 */
  private finishDish(order: Order, dish: Dish) {
    // 1. 改深层字段(@Trace 保证通知)
    dish.status = 'DONE'

    // 2. 若业务需要“整条订单完成”判断,可继续这里处理
    prompt.showToast({ message: `${dish.name} 已完成`, duration: 500 })
  }

  /* ========== UI ========== */
  build() {
    Column({ space: 12 }) {
      Text('深层 map 响应示例(@ObservedV2 + @Trace)')
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
        .margin(16)

      List({ space: 12 }) {
        ForEach(this.orders, (order: Order) => {
          ListItem() {
            this.OrderCard(order)
          }
        }, (order: Order) => order.id.toString())
      }
      .layoutWeight(1)
      .padding({ left: 16, right: 16 })
    }
    .backgroundColor('#F2F4F6')
    .height('100%')
  }

  @Builder
  OrderCard(order: Order) {
    Column({ space: 8 }) {
      Text(`订单 ID:${order.id}`).fontSize(16).fontWeight(FontWeight.Medium)

      /* 内层列表:每道菜 */
      ForEach(order.dishList, (dish: Dish) => {
        Row() {
          /* 深层字段变动 -> 自动刷新 */
          Text(`状态:${this.dishText(dish)}`)
            .fontColor(this.dishColor(dish))
            .fontSize(16)

          Blank().layoutWeight(1)

          if (dish.status !== 'DONE') {
            Button('完成')
              .height(28)
              .padding({ left: 12, right: 12 })
              .backgroundColor('#007DFF')
              .borderRadius(14)
              .onClick(() => this.finishDish(order, dish))
          }
        }
        .width('100%')

      }, (dish: Dish) => dish.id.toString())
    }
    .padding(12)
    .backgroundColor('#FFFFFF')
    .borderRadius(8)
    .shadow({ radius: 4, color: '#20000000', offsetX: 0, offsetY: 2 })
    .width('100%')
  }
}

错误代码

// 注意:实际开发中请使用正确的地图导入路径
// import map from '@hms.core.map.map';  // 如果不需要地图功能可暂时注释

@ObservedV2
class Shuju {
  @Trace id: number;  // 新增id用于区分对象
  @Trace status: string = '';
  @Trace  price: number = 0;

 constructor(id: number, status: string, price: number) {  // 新增id参数
    this.id = id;
    this.status = status;
    this.price = price;
  }
}

@Entry
@Component
struct Index {
  // 状态文本转换方法
  textstatus(item: Shuju): string {
    switch (item.status) {
      case 'nn':
        return '你好';  // 修正中文拼写
      case 'nj':
        return '你好呀'; // 更合理的中文显示
      default:
        return '未定义状态'; // 更友好的默认提示
    }
  }

  // 初始化数组,添加唯一id
  @State lizi: Shuju[] = [
    new Shuju(1, 'nj', 11),
    new Shuju(2, 'nj', 111),
    new Shuju(3, 'nj', 12)
  ];

  // 修改状态的方法
  xiugai(targetItem: Shuju) {
    // 使用map创建新数组,保持响应式
    this.lizi = this.lizi.map(item => {
      // 找到目标对象,创建新对象并修改状态(保持不可变更新)
      if (item.id === targetItem.id) {
        return new Shuju(item.id, 'nn', item.price);
      }
      return item;
    });

    console.log("修改后的状态:", targetItem.status);
    console.log("当前列表:", JSON.stringify(this.lizi));
  }

  build() {
    Column() {
      Text('状态列表演示')
        .fontSize(20)
        .margin(20)

      ForEach(
        this.lizi,
        (item: Shuju) => {
          Column({ space: 8 }) {
            Text(`当前状态:${this.textstatus(item)}`)
              .fontSize(16)
              .padding(10)
              .backgroundColor('#F5F5F5')
              .borderRadius(8)
              .width('80%')
              .textAlign(TextAlign.Center)

            Button('修改状态')
              .width('80%')
              .backgroundColor('#007DFF')
              .fontColor('#FFFFFF')
              .borderRadius(8)
              .onClick(() => this.xiugai(item))
          }
          .margin({ bottom: 12 })
        },
        (item: Shuju) => item.id.toString()  // 添加唯一key
      )
    }
    .height('100%')
    .width('100%')
    .padding(16)
    .backgroundColor('#F9F9F9')
  }
}

正确代码:

// Index.ets  (API 11+)
import { prompt } from '@kit.ArkUI';

/* ========== 深层观察模型 ========== */
@ObservedV2
class Shuju {
  @Trace id: number = 0
  @Trace status: string = ''
  @Trace price: number = 0

  constructor(id: number, status: string, price: number) {
    this.id = id
    this.status = status
    this.price = price
  }
}

/* ========== 页面 ========== */
@Entry
@Component
struct Index {
  @State lizi: Shuju[] = [
    new Shuju(1, 'nj', 11),
    new Shuju(2, 'nj', 111),
    new Shuju(3, 'nj', 12)
  ]

  private textStatus(item: Shuju): string {
    switch (item.status) {
      case 'nn': return '你好'
      case 'nj': return '你好呀'
      default: return '未定义'
    }
  }

  private statusColor(item: Shuju): string {
    return item.status === 'nn' ? '#00C853' : '#FFA500'
  }

  /* 直接改深层字段 → 立即刷新 */
  private xiugai(targetItem: Shuju) {
    targetItem.status = 'nn'          // @Trace 触发精准刷新
    prompt.showToast({ message: '已修改', duration: 500 })
  }

  build() {
    Column() {
      Text('状态列表演示')
        .fontSize(20)
        .margin(20)

      ForEach(this.lizi, (item: Shuju) => {
        Column({ space: 8 }) {
          Text(`当前状态:${this.textStatus(item)}`)
            .fontSize(16)
            .padding(10)
            .backgroundColor(this.statusColor(item))
            .fontColor('#FFFFFF')
            .borderRadius(8)
            .width('80%')
            .textAlign(TextAlign.Center)

          Button('修改状态')
            .width('80%')
            .backgroundColor('#007DFF')
            .fontColor('#FFFFFF')
            .borderRadius(8)
            .onClick(() => this.xiugai(item))
        }
        .margin({ bottom: 12 })
      }, (item: Shuju) => item.id.toString())
    }
    .height('100%')
    .width('100%')
    .padding(16)
    .backgroundColor('#F9F9F9')
  }
}

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐