HarmonyOS 数据刷新问题

使用了这个三方库ohpm install @ohos/liveeventbus。

使用代码如下:发现 @State eventBus:不能更新UI。

const KEY_TEST_CLOSE_ALL_PAGE = "key_test_close_all_page";

@Entry
@Component
struct EventBusPage {
  mLifecycle: Lifecycle = new Lifecycle(MState.STARTED);
  @State eventBus: boolean = false;

  aboutToAppear(): void {
    //创建生命周期感知对象
    this.mLifecycle = new Lifecycle(MState.STARTED)

    //订阅消息
    LiveEventBus
      .get<boolean>(KEY_TEST_CLOSE_ALL_PAGE)
      .observe(this, {
        onChanged(b: boolean) {
          this.eventBus = b;
        }
      });
  }

  build() {
    Row() {
      Column() {
        Text('LiveEventBus Demo' + this.eventBus)
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
      }.onClick((e) => {
        //发送消息
        LiveEventBus.get(KEY_TEST_CLOSE_ALL_PAGE).post( !this.eventBus);
      })
      .width('100%')
    }
    .height('100%')
  }

  //生命周期感知对象
  getLifecycle(): Lifecycle {
    return this.mLifecycle
  }
}
HarmonyOS
2024-12-11 14:24:16
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
aquaa

eventBus的使用请参考文档:https://gitee.com/openharmony-sig/LiveEventBus,demo中onchanged方法中的this对应的不是页面的this,所以不会发生变化可以参考此demo:

//引入
import { LiveEventBus,Lifecycle,MState } from '@ohos/liveeventbus'
const KEY_TEST_CLOSE_ALL_PAGE = "key_test_close_all_page";

@Entry
@Component
struct EventBusPage {
  mLifecycle: Lifecycle = new Lifecycle(MState.STARTED);
  @State eventBus: boolean = false;

  aboutToAppear(): void {
    //创建生命周期感知对象
    this.mLifecycle = new Lifecycle(MState.STARTED)

    //订阅消息
    LiveEventBus
      .get<boolean>(KEY_TEST_CLOSE_ALL_PAGE)
      .observe(this, {
        onChanged: (b: boolean) => {
          this.eventBus = b;
        }
      });
  }

  build() {
    Row() {
      Column() {
        Text('LiveEventBus Demo' + this.eventBus)
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
      }.onClick((e) => {
        //发送消息
        LiveEventBus.get(KEY_TEST_CLOSE_ALL_PAGE).post( !this.eventBus);
      })
      .width('100%')
    }
    .height('100%')
  }

  //生命周期感知对象
  getLifecycle(): Lifecycle {
    return this.mLifecycle
  }
}
分享
微博
QQ
微信
回复
2024-12-11 17:14:42
相关问题
HarmonyOS 页面数据刷新问题
191浏览 • 1回复 待解决
HarmonyOS LazyForEach数据刷新问题
206浏览 • 1回复 待解决
HarmonyOS swiper数据刷新问题
187浏览 • 1回复 待解决
HarmonyOS 列表刷新问题
878浏览 • 1回复 待解决
HarmonyOS 组件刷新问题
246浏览 • 1回复 待解决
HarmonyOS 页面刷新问题
590浏览 • 1回复 待解决
HarmonyOS webview刷新问题
274浏览 • 2回复 待解决
HarmonyOS ForEach列表刷新问题
369浏览 • 1回复 待解决
HarmonyOS List item 刷新问题
1047浏览 • 1回复 待解决
NativeWindowFlushBuffer接口刷新问题
2123浏览 • 1回复 待解决
HarmonyOS UI不刷新问题
296浏览 • 1回复 待解决
HarmonyOS @Builder UI刷新问题
235浏览 • 1回复 待解决
HarmonyOS 页面跳转刷新问题
1313浏览 • 1回复 待解决
HarmonyOS UI 未刷新问题
818浏览 • 0回复 待解决
HarmonyOS 组件的下拉刷新问题
747浏览 • 1回复 待解决
HarmonyOS使用Refresh下拉刷新问题
1161浏览 • 1回复 待解决
HarmonyOS 装饰器不刷新问题
404浏览 • 1回复 待解决
HarmonyOS 自定义弹窗刷新问题
230浏览 • 1回复 待解决
HarmonyOS ForEach创建的视图刷新问题
252浏览 • 1回复 待解决
HarmonyOS 二维数组刷新问题
617浏览 • 1回复 待解决