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 swiper数据刷新问题
917浏览 • 1回复 待解决
HarmonyOS 页面数据刷新问题
1574浏览 • 1回复 待解决
HarmonyOS LazyForEach数据刷新问题
932浏览 • 1回复 待解决
HarmonyOS 组件刷新问题
1024浏览 • 1回复 待解决
HarmonyOS 页面刷新问题
1393浏览 • 1回复 待解决
HarmonyOS webview刷新问题
1109浏览 • 1回复 待解决
HarmonyOS 列表刷新问题
1595浏览 • 1回复 待解决
HarmonyOS UI不刷新问题
1101浏览 • 1回复 待解决
HarmonyOS @Builder UI刷新问题
992浏览 • 1回复 待解决
HarmonyOS UI 未刷新问题
1696浏览 • 1回复 待解决
HarmonyOS 页面跳转刷新问题
2638浏览 • 1回复 待解决
NativeWindowFlushBuffer接口刷新问题
2746浏览 • 1回复 待解决
HarmonyOS List item 刷新问题
1775浏览 • 1回复 待解决
HarmonyOS ForEach列表刷新问题
1249浏览 • 1回复 待解决
HarmonyOS 装饰器不刷新问题
1153浏览 • 1回复 待解决
HarmonyOS 组件的下拉刷新问题
1436浏览 • 1回复 待解决
HarmonyOS使用Refresh下拉刷新问题
1869浏览 • 1回复 待解决
HarmonyOS 二维数组刷新问题
1311浏览 • 1回复 待解决
HarmonyOS ForEach创建的视图刷新问题
845浏览 • 1回复 待解决
HarmonyOS 自定义弹窗刷新问题
965浏览 • 1回复 待解决
HarmonyOS 状态变量不刷新问题
2013浏览 • 2回复 待解决