文档开发者中心
我的
|

ArkUI

父组件没有更新

已解决

【问题描述】:

弹窗出现后,会出现列表点击列表选项,要想切换第一个页面的值

例如:点击超市,第一个页面的值变成demo1超市

cke_173.png​​

这边在@Builder function buildType 的内部组件点击事件想要修改 IndexCommon 的值 但是这样写有点问题

​cke_2757.png

【问题现象】:没有报错

【版本信息】:编辑器  6.0.0

【复现代码】:最小复现问题的demo

【尝试解决方案】:

目前使用emitter.emit解决了 @Builder function buildType 与 IndexCommon父组件之间的通信接收修改值

但是页面值修改不了

IndexCommon.ets 的 @Builder function buildType

​

​

这边this.demoList[0] 直接复制只要是name 字段是demo1 页面的值就不会更改,手动将name 和desc 字符串赋值没问题

不一定需要我这个emitter.emit方式,还有其他方案也行

demo地址:https://gitcode.com/TerranASky/demoList

点赞
收藏
回复
4
分享
举报
浏览130 发布于2025-12-23 10:29湖北
全部评论
最多点赞
最新发布
最早发布
|
采纳答复

【解决方案】

楼主,ForEach中的第三个参数keyGenerator使用不恰当,数据源数组项发生变化时,如果键值生成函数中的返回值没有发生改变,不会触发UI实时刷新。

src/main/ets/pages/IndexCommon.ets中ForEach的key生成规则改一下再试一下,我这边测试是可以了

收起
自动换行
深色代码主题
复制
build() {
    Column() {
      List({ space: 8 }) { // 减小space让分组更紧凑
        ForEach(this.demoList, (item: DemoVo) => {
          ListItem(){
            Row() {
              Text(item.name)
              Text(item.desc)
            }
            .backgroundColor(Color.White)
            .borderRadius(20)
            .onClick(() => {
              PromptAction.setContentNode(new ComponentContent(this.ctx, wrapBuilder(buildType),
                new Params(this.demoList, this.dialogShowList,this.ctx)));
              PromptAction.openDialog()
            })
          }
        }, (item: DemoVo) => item.name+item.desc)
      }
    }
  }

【背景知识】

  • ForEach接口基于数组类型数据来进行循环渲染,需要与容器组件配合使用,且接口返回的组件应当是允许包含在ForEach父容器组件中的子组件。
  • 被@State修饰的变量可以触发其直接绑定UI组件的刷新,当状态改变即数据改变时,UI会发生对应的渲染改变,但并不是所有被@State修饰的变量都会引起UI的刷新,只有被框架观察到的修改才会引起UI刷新。
展开全部
2楼回复于2025-12-25 08:06 来自广东

提供一个新的解决方案,亲测有效的:
以下是调整点:

1. 注意看注释的地方

收起
自动换行
深色代码主题
复制
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  @State demoList: DemoVo[] =[new DemoVo('demo1','医院')]
  private storeManager = StoreManager.getInstance()
  @State currentIndex: string = ''  // 增加行

  aboutToAppear(): void {
    this.storeManager.initDB(getContext(this))
      .then(() => {
        this.storeManager.getCodeSizeList().then((data) => {
          if (data.length > 0) {
            this.demoList = [
              new DemoVo('demo1', data[0].desc)
            ]
          } else {
            this.storeManager.addCodeSizeInfo().then((data) => {
              this.demoList = [
                new DemoVo('demo1', data[0].desc)
              ]
            })
          }
        }).catch((err: BusinessError) => {
        })
      })
      .catch()
  }

  build() {
    Column() {
      Text(`demo:` + this.currentIndex) // 增加行--在最外层更新
      IndexCommon({ demoList: this.demoList, selectItem: this.currentIndex })
    }
    .width('100%')
    .height('100%')
  }
}

2.注意看注释的地方

收起
自动换行
深色代码主题
复制
class Params implements DialogConfig {
  list: DemoVo[] | null
  list2: DialogShow[]
  context: UIContext
  eventBack: (index: number) => void = () => {} // 增加行

  constructor(list: DemoVo[] | null, list2: DialogShow[],context : UIContext, eventBack: (index: number) => void) {
    this.list = list
    this.list2 = list2
    this.context = context
    this.eventBack = eventBack  // 增加行
  }
}

3.注意看注释的地方

收起
自动换行
深色代码主题
复制
@Component
export struct IndexCommon {
  @State demoList: DemoVo[] = []  // 调整行
  private ctx: UIContext = this.getUIContext();
  private dialogShowList: DialogShow [] = [
    new DialogShow('医院'),
    new DialogShow('超市'),
    new DialogShow('公司'),
    new DialogShow('商场'),
    new DialogShow('学校'),
  ]

  @Link selectItem: string  // 增加行


  async aboutToAppear(): Promise<void> {
    PromptAction.setContext(this.ctx);
    PromptAction.setOptions({ alignment: DialogAlignment.Center, offset: { dx: 0, dy: 0 } });
    let event: emitter.InnerEvent = {
      eventId: 1
    };

    // Execute the callback after receiving an event with eventId 1
    let callback = (eventData: emitter.EventData): void => {
      console.log(JSON.stringify(eventData.data?.demoList))
      // this.demoList = eventData.data?.demoList
      let eveDataList : DemoVo = eventData.data?.demoList[0]
      let eveName = eveDataList.name
      let eveDesc = eveDataList.desc
      console.log(eveName+eveDesc)
      let newDemoVe : DemoVo = new DemoVo(eveName,'asdasdasd')
      this.demoList[0] = newDemoVe
      // this.getUIContext().getPromptAction().showToast({
      //   message: JSON.stringify(this.demoList)
      // });
    };

    // Subscribe to events with eventId 1
    // emitter.on(event,callback);   // 需要注释之前的更新方式
    this.getUIContext().getPromptAction().showToast({
      message: 'subscribe_success'
    });

  }


  build() {
    Column() {
      List({ space: 8 }) { // 减小space让分组更紧凑
        ForEach(this.demoList, (item: DemoVo) => {
          ListItem(){
            Row() {
              Text(item.name)
              Text(item.desc)
            }
            .backgroundColor(Color.White)
            .borderRadius(20)
            .onClick(() => {
              PromptAction.setContentNode(new ComponentContent(this.ctx, wrapBuilder(buildType),
                new Params(this.demoList, this.dialogShowList,this.ctx, (index: number) => {
                  this.selectItem = this.dialogShowList[index].desc  // 增加行- 在最外层更新
                  this.demoList = []  // 增加行
                  this.demoList = [new DemoVo('demo1', this.dialogShowList[index].desc)]  // 增加行- 初始更新逻辑在最外层更新
                })));
              PromptAction.openDialog()
            })
          }
        })
      }
    }
  }
}

4.注意看注释的地方

收起
自动换行
深色代码主题
复制
// 弹窗
@Builder
function buildType(params: Params) {
  Column({ space: 0 }) {
    ForEach(params.list2, (item: DialogShow, index: number) => {
      Column({ space: 0 }) {
        // 描述部分
        Text(item.desc)
          .fontSize($r('sys.float.Body_M'))
          .fontColor('#666666')
          .textAlign(TextAlign.Start)
          .layoutWeight(2)
          .maxLines(1)
          .textOverflow({ overflow: TextOverflow.MARQUEE })
      }
      .width('100%')
      .height(56)
      .justifyContent(FlexAlign.Start)
      .padding({ left: 16, right: 16 })
      .onClick(() => {
        params.eventBack(index) // 增加行

        StoreManager.getInstance().updateCodeSizeInfoByType('demo1', item.desc).then((value) => {
          // IndexCommon({
          //   demoList: [
          //     new DemoVo('demo1', value[0].desc),
          //   ]
          // })
          let event: emitter.InnerEvent = {
            eventId: 1,
            priority: emitter.EventPriority.LOW
          };

          let eventData: emitter.EventData = {
            data: {
              content: 'c',
              id: 1,
              isEmpty: false,
              demoList: [
                new DemoVo('demo1', value[0].desc),
              ]
            }
          };
          // Send an event with eventId 1 and the event content is eventData
          emitter.emit(event,eventData);

        })
        PromptAction.closeDialog()
      })
    })
  }
}
展开全部
3楼回复于2025-12-25 08:43 来自上海

直接修改对象属性(如this.demoList.desc)无法触发UI更新,ArkUI的响应式系统需要对象引用变更

可以尝试

收起
自动换行
深色代码主题
复制
// 父组件 Index.ets
@Component
struct Index {
  @State demoList: DemoVo[] = [new DemoVo('demo1', '医院')]

  build() {
    Column() {
      // 使用@Link实现双向绑定
      IndexCommon({ demoList: $demoList })
    }
  }
}

// 子组件 IndexCommon.ets
@Component
export struct IndexCommon {
  @Link demoList: DemoVo[]

  @Builder buildType() {
    Button('修改值')
      .onClick(() => {
        // 正确方式:创建新数组触发响应式更新
        const newList = [...this.demoList]
        newList = new DemoVo('demo1', '超市')
        this.demoList = newList
      })
  }
}
展开全部
1
1楼回复于2025-12-25 03:11 来自安徽
  • 周天
    我的buildType builder 是一个全局的,不能放入父组件内部,然后去this.demoList 去更改
    2025-12-25 08:00 来自湖北
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。

我要提问题

了解社区公约,与您携手共创和谐专业的开发者社区。