采用@Provide装饰器声明了一个状态变量,通过其它类提供的方法实现数据修改,但是没有触发UI刷新,页面上的数据没有改变。
import currentPlayInfo, { PlayInfo } from './PlayInfo' import player from './AVPlayer' @Entry @Component struct Index { @Provide('pageStack') pageStack: NavPathStack = new NavPathStack() @Provide('playInfo') playInfo: PlayInfo = currentPlayInfo build() { Navigation(this.pageStack) { Column() { if (this.playInfo.isPlaying) { Text('正在播放' + this.playInfo.title) .fontSize(50) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: '__container__', align: VerticalAlign.Center }, middle: { anchor: '__container__', align: HorizontalAlign.Center } }) } else { Text('没有播放') .fontSize(30) } Text('Change PlayInfo') .fontSize(30) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: '__container__', align: VerticalAlign.Center }, middle: { anchor: '__container__', align: HorizontalAlign.Center } }) .onClick(() => { player.play(); }) } .height('100%') .width('100%') } .hideTitleBar(true) } }
点击“Change PlayInfo”文本时,希望文本“没有播放”更新为“正在播放第XX首”,问题现象如下图所示:


应将AVPlayer类中play()函数修改的普通变量currentPlayInfo替换为状态变量playInfo。由于状态变量playInfo并不是全局实例对象,无法通过引用导入的方式修改,所以通过重写play()方法,在调用时传入状态变量playInfo并修改。修改如下:
export class PlayInfo { isPlaying: boolean = false; title: string = ''; } let currentPlayInfo = new PlayInfo(); export default currentPlayInfo as PlayInfo;
import currentPlayInfo, { PlayInfo } from './PlayInfo'; import player from './AVPlayer'; @Entry @Component struct Index { @Provide('pageStack') pageStack: NavPathStack = new NavPathStack(); @Provide('playInfo') playInfo: PlayInfo = currentPlayInfo; build() { Navigation(this.pageStack) { Column() { if (this.playInfo.isPlaying) { Text('正在播放' + this.playInfo.title) .fontSize(50) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: '__container__', align: VerticalAlign.Center }, middle: { anchor: '__container__', align: HorizontalAlign.Center } }); } else { Text('没有播放') .fontSize(30); } Text('Change PlayInfo') .fontSize(30) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: '__container__', align: VerticalAlign.Center }, middle: { anchor: '__container__', align: HorizontalAlign.Center } }) .onClick(() => { // 需要修改的是状态变量,以实现驱动UI更新的效果 player.playNew(this.playInfo as PlayInfo); }); } .height('100%') .width('100%'); } .hideTitleBar(true); } }