harmony Next中怎么局部刷新UI

114 阅读1分钟

示例图片.jpg 假设要做一个抖音的短视频页面,在处理点赞,评论,收藏这些操作的时候,不要影响视频的正常播放,你会怎么处理呢? 我们视频渲染组件用的是

XComponent({
  id: this.extraParam + this.playerIndex.toString(),
  type: XComponentType.SURFACE,
  libraryname: 'premierlibrary',
  controller: this.xComponentController
})

harmony原生的XComponent组件,它的id必须是唯一的,就是id不能重复使用,id一旦重复,视频的画面就会播放不出来. 所以在点赞,收藏,评论操作中刷新整个页面的数据,视频渲染就会受影响.最开始想的办法是在操作点赞,收藏,评论的时候改变XComponent的id,这样虽然也能解决问题,但是太繁琐.最后想到的办法是再声明一个@state修饰的变量.

@State curShowVideoItem: VideoListItem | PostVideoListDataListItem | undefined = undefined;

切换视频的时候给它赋值

private onIndexChange() {
  const curIndex = this.index;
  if (this.videoListPageDataSource.totalCount() > 0) {
    this.curShowVideoItem = this.videoListPageDataSource.getData(curIndex);
  } else {
    this.curShowVideoItem = this.postVideoListPageDataSource.getData(curIndex);
  }
}

然后和点赞,收藏,评论相关的UI写在这个判断下

if (undefined != this.curShowVideoItem)

UI的值也用的是这个curShowVideoItem变量的值,在点赞操作的时候

const curHandleVideoItem = this.videoListPageDataSource.getData(this.index);
curHandleVideoItem.praiseFlag = true
curHandleVideoItem.praises = curHandleVideoItem.praises as number + 1
this.curShowVideoItem = curHandleVideoItem

这样操作,就会改变点赞相关操作UI的状态,而不是刷新页面所有的东西.