HarmonyOS 用@Watch来订阅数据变化时候,数据中每个属性变化都会导致调用这个@Watch方法

当我从一个页面给子组件传递参数时,需要用到@Watch,但是当@Watch的变量里面的字段一个个重新赋值时候,会导致每次都会调用@Watch,导致多次触发,请问有什么办法能避免每次都触发调用方法吗?

比如:

this.newsInfo.NewsType = NewsType.LIVE_TEXT_TYPE 
this.newsInfo.NewsTitle = this.liveInfo.LiveTitle 
this.newsInfo.NewsID = this.liveInfo.LiveID 
this.newsInfo.CreateDate = this.liveInfo.CreateDate 
this.newsInfo.Stocks = this.liveInfo.Stocks 
this.newsInfo.NewsHot = this.liveInfo.NewsHot

这边我需要将liveInfo中的数据赋值给newsInfo,然后子组件中我会订阅newsInfo的数据变化来进行数据请求,现在会导致多次请求。

之所以用这种方法是因为newsInfo也是网络请求回来的,我需要通知子组件这个数据请求到了子组件中也可以开始请求数据。

父组件代码:

@State newsInfo: NewsEntity = new NewsEntity() 
this.newsInfo.NewsType = NewsType.LIVE_TEXT_TYPE 
this.newsInfo.NewsTitle = this.liveInfo.LiveTitle 
this.newsInfo.NewsID = this.liveInfo.LiveID 
this.newsInfo.CreateDate = this.liveInfo.CreateDate 
this.newsInfo.Stocks = this.liveInfo.Stocks

传递给子组件

CommentBottomBar({ newsEntity: $newsInfo})

子组件代码:

@Link @Watch('newsEntitySuccess') newsEntity: NewsEntity 
newsEntitySuccess() { 
      request(newsEntity.NewsID) 
  }
HarmonyOS
2024-08-30 12:44:09
浏览
收藏 0
回答 2
待解决
回答 2
按赞同
/
按时间
rose_bestOne

是否可以实现只监听newsEntity.NewsID

分享
微博
QQ
微信
回复
2024-08-30 14:31:42
FengTianYa

可以参考以下demo:

@Observed 
class tmp { 
 count: number = 0 
 name: string = 'ahah' 
} 
 
@Component 
struct watchShuXingChild { 
 @Link @Watch('exampleWatch') exampleChild: tmp 
 @State @Watch('idWatch') idChild: Length = 0; 
 @State countChild: Length = 0 
 
 exampleWatch(propName: string): void { 
  console.log('exampleWatch:', this.exampleChild.count.toString()); 
  this.idChild = this.exampleChild.count 
 } 
 
 idWatch(propName: string): void { 
  console.log('idWatch'); 
  this.countChild = this.idChild 
 } 
 
 build() { 
  Column() { 
   Text(`子组件id${this.countChild}`).fontSize(30) 
  } 
 } 
} 
 
@Entry 
@Component 
struct watchShuXing { 
 @State example: tmp = new tmp(); 
 @State idR: number = 0 
 
 build() { 
  Column() { 
   Text(`改变属性${this.example.count}`) 
    .onClick(() => { 
     this.example.count++ 
    }).fontSize(30) 
 
   Text(`改变属性name${this.example.name}`) 
    .onClick(() => { 
     this.idR++ 
     this.example.name = this.example.name + this.idR 
    }).fontSize(30) 
   watchShuXingChild({ exampleChild: this.example }) 
  } 
 } 
}

可以监听id,这样父组件的其他属性改变,只要id不变,watch就不会触发。

分享
微博
QQ
微信
回复
2024-08-30 19:55:19
相关问题
HarmonyOS数据数据变化是否可以监听
216浏览 • 1回复 待解决
如何订阅系统环境变量的变化
172浏览 • 1回复 待解决
如何监听数组内对象属性变化
1981浏览 • 1回复 待解决
如何取消订阅输入法文本内容的变化
118浏览 • 1回复 待解决
Watch GT2什么时候可以升级鸿蒙
6879浏览 • 1回复 待解决
在@watch中使用异步方法后UI反应慢
152浏览 • 1回复 待解决
UIAbility是否可以监听页面变化
1235浏览 • 1回复 待解决
@Watch异常有了解的吗?
2545浏览 • 1回复 待解决