文档里关于StorageLink的描述的疑问?

文档内容:
使用该机制来实现事件通知需要确保AppStorage中的变量尽量不要直接绑定在UI上,且需要控制@Watch函数的复杂度(如果@Watch函数执行时间长,会影响UI刷新效率)。

以上通知事件逻辑简单,也可以简化成三元表达式。

// xxx.ets  
class ViewData {  
title: string;  
uri: Resource;  
color: Color = Color.Black;  
  
constructor(title: string, uri: Resource) {  
this.title = title;  
this.uri = uri  
}  
}  
  
@Entry  
@Component  
struct Gallery2 {  
dataList: Array<ViewData> = [new ViewData('flower', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon'))]  
scroller: Scroller = new Scroller()  
  
build() {  
Column() {  
Grid(this.scroller) {  
ForEach(this.dataList, (item: ViewData, index?: number) => {  
GridItem() {  
TapImage({  
uri: item.uri,  
index: index  
})  
}.aspectRatio(1)  
  
}, (item: ViewData, index?: number) => {  
return JSON.stringify(item) + index;  
})  
}.columnsTemplate('1fr 1fr')  
}  
  
}  
}  
  
@Component  
export struct TapImage {  
@StorageLink('tapIndex') tapIndex: number = -1;  
private index: number = 0;  
private uri: Resource = {  
id: 0,  
type: 0,  
moduleName: "",  
bundleName: ""  
};  
  
build() {  
Column() {  
Image(this.uri)  
.objectFit(ImageFit.Cover)  
.onClick(() => {  
this.tapIndex = this.index;  
})  
.border({  
width: 5,  
style: BorderStyle.Dotted,  
color: (this.tapIndex >= 0 && this.index === this.tapIndex) ? Color.Red : Color.Black  
})  
}  
}  
}

本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。

阅读 732
avatarAI BotBETA

回答

文档中关于StorageLink的描述强调了在实现事件通知时需要注意的两个方面:

  1. 避免直接将AppStorage中的变量绑定在UI上

    • 这是因为频繁的UI更新可能会导致性能问题。如果AppStorage中的变量直接绑定到UI组件上,每当这些变量的值发生变化时,UI组件都会重新渲染。如果这种变化非常频繁,会严重影响应用的性能。
  2. 控制@Watch函数的复杂度

    • @Watch函数用于监听AppStorage中变量的变化。如果@Watch函数的执行逻辑过于复杂或耗时,当监听到的变量发生变化时,UI的刷新效率会受到影响,可能导致界面卡顿或响应不及时。

在提供的代码示例中,TapImage组件使用了@StorageLink('tapIndex')来监听tapIndex变量的变化,并根据该变化更新UI(即改变图片的边框颜色)。这里并没有直接将AppStorage中的变量绑定在UI上,而是通过@StorageLink@Watch机制间接地实现了事件通知和UI更新。同时,@Watch函数(虽然示例中没有直接展示,但隐含在@StorageLink的使用中)的复杂度应该相对较低,仅涉及简单的变量比较和UI更新逻辑,因此不会影响UI的刷新效率。

1 个回答

借助@StorageLink的双向同步机制实现事件通知,可以使用Emitter订阅某个事件并接收事件回调的方式来减少开销。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进