鸿蒙V1 & V2 状态管理第一弹:@State篇

使用场景:

1.装饰简单类型 量

@Entry
@Component
struct WeatherDemo {
  @State temperature: number = 25

  // 当状态变量temperature改变时,只能查询到Button组件与之关联。
  //执行Button组件的更新方法,实现按需刷新。

  build() {
    Column() {
      Text(`当前温度:${this.temperature}℃`)
        .fontSize(22)
        .margin(20)
      Button('升温')
        .margin(10)
        .onClick(() => {
          this.temperature += 1
        })
      Button('降温')
        .margin(10)
        .onClick(() => {
          this.temperature -= 1
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
    .alignItems(HorizontalAlign.Center)
  }
}

2.装饰class对象类型的变量

@State 装饰 class 对象类型变量的基本原理

  • 被 @State 装饰的变量,无论是基本类型(如 number、string),还是对象类型(如 class 实例),当变量的“引用”发生变化时,UI 会自动刷新。
  • 如果你直接修改对象的属性(如 this.weather.desc = '多云'),UI 不一定会刷新,因为对象的引用没有变。
  • 只有当你给 @State 变量赋予一个新的对象实例时(如 this.weather = new WeatherModel(...)),UI 才会感知到变化并刷新。
  • 注意:类的属性要么在声明时赋初值,要么在构造函数里明确赋值,否则会报错。

class WeatherModel {
  public desc: string
  public icon: string

  constructor(desc: string, icon: string) {
    this.desc = desc
    this.icon = icon
  }
}

@Entry
@Component
struct EntryComponent {
  build() {
    Column() {
      WeatherComponent({ temperature: 25, weather: new WeatherModel('晴', '☀️') })
        .width(300)
        .margin(10)
      WeatherComponent({ temperature: 18, weather: new WeatherModel('多云', '⛅') })
        .width(300)
        .margin(10)
    }
  }
}

@Component
struct WeatherComponent {
  @State temperature: number = 0
  @State weather: WeatherModel = new WeatherModel('晴', '☀️')

  build() {
    Column() {
      Row({ space: 10 }) {
        Text(this.weather.icon)
          .fontSize(36)
        Text(`${this.temperature}`)
          .fontSize(48)
          .fontWeight(FontWeight.Bold)
        Text('℃')
          .fontSize(24)
          .fontColor(0x888888)
      }
      Text(`天气:${this.weather.desc}`)
        .fontSize(20)
        .margin(10)
      Row({ space: 20 }) {
        Button('升温')
          .type(ButtonType.Capsule)
          .backgroundColor(0xFFF3E0)
          .fontColor(0xE65100)
          .onClick(() => {
            this.temperature += 1
          })
        Button('降温')
          .type(ButtonType.Capsule)
          .backgroundColor(0xE0F7FA)
          .fontColor(0x00796B)
          .onClick(() => {
            this.temperature -= 1
          })
        Button('切换天气')
          .type(ButtonType.Capsule)
          .backgroundColor(0xE3F2FD)
          .fontColor(0x1976D2)
          .onClick(() => {
            if (this.weather.desc === '晴') {
              this.weather = new WeatherModel('多云', '⛅')
            } else if (this.weather.desc === '多云') {
              this.weather = new WeatherModel('小雨', '🌧️')
            } else {
              this.weather = new WeatherModel('晴', '☀️')
            }
          })
      }
    }
    .width('100%')
    .height(200)
    .justifyContent(FlexAlign.Center)
    .alignItems(HorizontalAlign.Center)
    .backgroundColor(0xF5F5F5)
    .margin(10)
    .borderRadius(16)
  }
}

从该示例中,我们可以了解到@State变量的初始化机制:

  1. 没有外部传入的情况下,使用默认的值进行本地初始化:
@Component
struct WeatherComponent {
  @State temperature: number = 0
  @State weather: WeatherModel = new WeatherModel('晴', '☀️')

  build() {
    // ...UI代码...
  }
}
  • 这里 temperature 和 weather 都被 @State 装饰,并有默认值。
  • temperature 默认是 0,weather 默认是 new WeatherModel('晴', '☀️')。

2.在有外部传入的情况下,使用外部传入的值进行初始化:

@Entry
@Component
struct EntryComponent {
  build() {
    Column() {
      WeatherComponent({ temperature: 25, weather: new WeatherModel('晴', '☀️') })
        .width(300)
        .margin(10)
      WeatherComponent({ temperature: 18, weather: new WeatherModel('多云', '⛅') })
        .width(300)
        .margin(10)
    }
  }
}
  • 如果你传入了参数(如 temperature: 25、weather: new WeatherModel('晴', '☀️')),       ——组件内部的 @State 变量会用你传入的值进行初始化,覆盖本地默认值。
  • 如果你没有传入参数(比如 WeatherComponent()),                                                    ——组件内部的 @State 变量会使用本地默认值进行初始化。                                      ——@State temperature: number = 0

具体到案例

第一个 WeatherComponent({ temperature: 25, weather: new WeatherModel('晴', '☀️') })

  • ——temperature 初始化为 25
  • ——weather 初始化为 new WeatherModel('晴', '☀️')

第二个 WeatherComponent({ temperature: 18, weather: new WeatherModel('多云', '⛅') })

  • ——temperature 初始化为 18
  • ——weather 初始化为 new WeatherModel('多云', '⛅')

如果你再加一个 WeatherComponent(),则:

  • temperature 初始化为 0(默认值)
  • weather 初始化为 new WeatherModel('晴', '☀️')(默认值)

总结

  • 有外部传入时,@State 变量用外部值初始化。
  • 无外部传入时,@State 变量用本地默认值初始化。
  • 每个组件实例的 @State 状态互不影响,互相独立。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值