前端鸿蒙按钮必须双击才能获取数据问题

问题描述:比如以下一看就很复杂的代码,但是其实关键在于taskApi.getTaskInformationByTaskId(this.taskFirstId).then((data)函数的调用影响按钮的实现,所以对按钮点击来说它需要使用 await 来等待 taskApi.getTaskInformationByTaskId 的异步结果。然后会提示你以下变化

.onClick(async () => 

这是因为在使用异步函数处理时,即在处理异步操作时,通常会将按钮点击事件处理程序定义为异步函数,并在需要时使用 await 关键字等待异步操作完成,即async/await组合。

      Row() {
                          Image(item.icon)
                        .width(35)
                        .height(35)
                        .margin(10)
                        .borderRadius(35)
                      Text(item.name).fontSize(20)
                    }.width('100%').height('50vp')
                    .justifyContent(FlexAlign.Start)
                    .onClick(() => {
                     //调用函数
                      this.taskFirstId=item.key;
                      // 获取对应任务id的时间数组、高度数组
                      this.coordinateQuery=[];
                      taskApi.getTaskInformationByTaskId(this.taskFirstId).then((data) => {
                        this.coordinateQuery = data.data;

                        // 初始化为一个空数组
                        this.times = [];
                        this.heights=[];
                        this.expectedHeights=[];
                        //期望每隔50条数据取一个存储到数组里面,但是这个逻辑感觉有点bug
                        for (let i = 0,j=0; i < this.coordinateQuery.length&&j<10; i += 10,j++) {
                      
                          this.coordinateQuery.slice(i, i+1).forEach((item) => {
                            // 创建taskShow对象完成,提取时间的最后两位
                            const timeLastTwoDigits:string = "第"+ item.createTime.slice(-2)+"秒";
                            this.times.push(timeLastTwoDigits);
                            this.heights.push(item.z);
                            this.expectedHeights.push(item.expectAltitude);
                          });
                        }
                       
                        this.defOption.xAxis.data = this.times;//在此进行赋值
                        //预计高度
                        this.defOption.series[0].data=this.expectedHeights;
                        //实际高度
                        this.defOption.series[1].data=this.heights;
                       
                      }).catch((error) => {
                        console.log('XYQError fetching jobs: ', error);
                      });
                      // this.ccc();
                      this.ccc2();

                      console.log(`点击了任务: ${this.taskFirstId}`);

                    })

猜你喜欢

转载自blog.csdn.net/m0_63229791/article/details/140363628