最近在使用鸿蒙开发时,碰到了一些坑,特做记录,如:鸿蒙的preview不能预览,轮播图组件Swiper使用时的问题,console.log() 打印的内容

一、鸿蒙的preview不能预览

首先,只有 ets文件才能预览。

其次,你的保证你电脑的内存足够(建议16G的内存以上),并且可用内存足够

再次

1)、文件--->设置--->构建,执行,部署----->构建工具--->Hvigor。  勾选最后一项:

         file---->settings-->build,Execution,Deployment--->build Tools----->Hvigor  勾选最后一项:Enable the Daemon fo tasks

2)、如果显卡没有问题的话,升级显卡驱动,然后在升级openGL。

二、轮播图组件Swiper使用时的问题

如果使用Swiper时,总是在切换组件时报错。尝试用List替换,自己实现轮播图的效果,如下:

import http from '@ohos.net.http';


@Entry
@Component
  // 对外开放
export default struct Home {

  @State imgs: Array<string> = [];
  scroller: Scroller = new Scroller()

  // 创建http的请求对象
  httpRequest = http.createHttp();

  // 获取轮播图数据
  getBanners(){

    this.httpRequest.request("http://localhost:3000/bannerImgs",(err,data)=>{
      if(!err){
        this.imgs = JSON.parse(data.result as string);
        this.initScroll();
      }
    })
  }

 

  // aboutToAppear():这个生命周期钩子函数的调用时机:当本页面(组件)加载时,
  aboutToAppear(){

    this.getBanners();
  }

  // 自行实现轮播图功能:
  initScroll(){
    let index = 0;
    let maxIndex = this.imgs.length-1;
    setInterval(()=>{
      index++;
      if(index>maxIndex){
        index = 0;
      }
      this.scroller.scrollTo({
        xOffset:index*400,
        yOffset:0,
        animation:{
          duration:1000,
          curve:Curve.Linear
        }
      })
    },2000)
  }

  build() {
    // 最外层使用弹性盒布局,纵向分为三部分:搜索框,滚动容器,底部。
    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween }) {
     
    
          // 1)、轮播图
          List({scroller:this.scroller}){
            ForEach(this.imgs,(item)=>{
              ListItem(){
                Image(item)
                  .width(400)
                  .height("100%")
              }
            })
          }
          .width("100%")
          .height(250)
          .listDirection(Axis.Horizontal)

        

    }
    .width("100%")
    .height("100%")
  }
}

三、console.log() 打印的内容

       经过测试,console.log()打印字符串时,碰到 斜杠后,就不再显示,但是数据在,所以,不必在意,当然,你可以尝试把字符串显示在界面上,进行验证 

四、ForEach函数的第三个参数

在循环json数组时,如果写上第三个参数,使用数组的某项拿出数据时,再做进一步运算时,会失去响应式,

解决方案:

1、去掉ForEach的第三个参数

2、数组的每一项用下标的方式访问。

五、发送请求

如果,用DevEco工具在预览项目时,如果根本不能发送请求时,可以进行权限的配置。

1、打开文件:

项目目录\entry\src\main\module.json5

2、增加如下代码:

{
    "module" : {
        ………………

        "requestPermissions":[
           {
             "name": "ohos.permission.INTERNET"
           }
        ]
        …………………

    }
}

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐