HarmonyOS鸿蒙Next中使用组件传递两个参数时@Watch监视其中一个参数,修改另一个参数会执行监视函数
HarmonyOS鸿蒙Next中使用组件传递两个参数时@Watch监视其中一个参数,修改另一个参数会执行监视函数
子组件中只监视了 text 数组,同时传递 flag 改变 flag 时会执行 func 函数;将 text 数组改成简单数组时又不会执行
export interface Nav {
id: number
name: string
}
@Entry
@Component
struct test {
@State text: Nav[] = [
{ id: 1, name: '1' },
{ id: 2, name: '3' },
{ id: 3, name: '4' },
{ id: 4, name: '2' },
]
@State current: number = 0
@State flag: boolean = false
build() {
Column() {
Button('改变current')
.onClick(() => this.current = (this.current + 1) % 4)
Button('改变flag')
.onClick(() => {
this.flag = !this.flag
console.log('父组件中的flag',this.flag.toString())
})
myCom({ flag: this.flag, text: this.text[this.current] })
// myCom({ flag: this.flag, text1: ['1','3','4','2'][this.current] })
}
}
}
@Component
struct myCom {
@Prop flag: boolean
@Prop
[@Watch](/user/Watch)("func")
text: Nav
@State text_a: string[] = Array.from({ length: 3 })
func() {
console.log('子组件中的flag',this.flag)
this.text_a[0] = this.text.name + '8'
this.text_a[1] = this.text.name + '9'
this.text_a[2] = this.text.name + '7'
if (this.flag)
this.text_a.sort()
}
aboutToAppear(): void {
console.log('页面生销了',)
this.func()
}
build() {
Column() {
ForEach(this.text_a, (item: string) => {
Text(item)
.fontSize(30)
.onClick(()=>console.log('子组件中的flag2',this.flag))
})
}
}
}
更多关于HarmonyOS鸿蒙Next中使用组件传递两个参数时@Watch监视其中一个参数,修改另一个参数会执行监视函数的实战教程也可以访问 https://www.itying.com/category-93-b0.html
你这func有两种触发方式:
1、@Watch在text属性变化时触发;
2、子组件 myCom 刷新时其aboutToAppear()中会调用;
你改变flag会触发myCom刷新,因为传递的@Prop flag属性有单向绑定,因此触发方式2执行了func,不是因为监视而触发。
想让flag改变不触发监控函数,去掉aboutToAppear()中的调用。
更多关于HarmonyOS鸿蒙Next中使用组件传递两个参数时@Watch监视其中一个参数,修改另一个参数会执行监视函数的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
Prop单向绑定的数据改变不会引起组件生销吧,我的aboutToAppear函数中有打印一句话,改变flag并没有打印;而且aboutToAppear不调用func也会出现这个情况,
我是API 11,@Prop可以修饰复杂变量,并且可以同步第一层UI更新,具体可以参考以下文档:
https://docs.openharmony.cn/pages/v4.0/zh-cn/application-dev/quick-start/arkts-prop.md
目前主要问题在于@Watch,会受同组件传输的其他未受监视的参数影响,点击第二个按钮后只改变了未受监视的flag,但是会触发func()函数,
在HarmonyOS鸿蒙Next中,使用@Watch
装饰器监视组件中的某个状态变量时,当被监视的变量发生变化,@Watch
装饰的函数会被触发执行。如果在组件中传递了两个参数,并且使用@Watch
监视其中一个参数,那么当另一个参数发生变化时,@Watch
监视的函数不会被执行,除非被监视的参数也发生了变化。
例如,假设有两个参数param1
和param2
,并且使用@Watch
监视param1
:
@Watch('param1')
onParam1Changed(newValue: any, oldValue: any) {
// 当param1发生变化时执行
}
在这种情况下,只有当param1
的值发生变化时,onParam1Changed
函数才会被调用。如果param2
的值发生变化,而param1
的值保持不变,onParam1Changed
函数不会被执行。
如果需要同时监视两个参数的变化,可以分别对param1
和param2
使用@Watch
装饰器,或者在onParam1Changed
函数中手动检查param2
的值是否发生了变化。
在HarmonyOS鸿蒙Next中,使用@Watch
监视组件参数时,如果修改了另一个未被监视的参数,不会触发监视函数。@Watch
仅对指定的参数变化做出响应。例如:
@Component
struct MyComponent {
@State param1: string = 'value1';
@State param2: string = 'value2';
@Watch('param1')
onParam1Changed() {
console.log('param1 changed');
}
build() {
// UI构建逻辑
}
}
在上述代码中,只有param1
的变化会触发onParam1Changed
,修改param2
不会触发该函数。