【taro】taro使用React.lazy懒加载组件,微信小程序动态导入失败(报错)

问题描述

公司项目需要动态加载ucharts的组件,我使用react.lazy懒加载组件,在h5环境下是可以正常显示,但是在微信小程序,他就报错说找不到该组件,后来查了taro官网才知道,微信小程序不能懒加载,只能提前一次性加载完进行调用(意思就是import xx from “组件名”)
以下代码就是运行微信小程序时报的错误。报错意思就是找不到该模块,但是我文件的确是有的
在这里插入图片描述
在这里插入图片描述
不兼容微信小程序的错误代码
在这里插入图片描述

解决流程

在代码中判断当前运行的环境(h5还是微信小程序),然后针对性的对微信小程序上的组件进行动态加载处理

import G_Bar from "@/components/Form/Bar"
import G_Line from "@/components/Form/Line"
import G_Pie from "@/components/Form/Pie"
const Hoc = (props: any) => {
  return class Wrap extends React.Component {
    constructor(props: any) {
      super(props)
    }
    render() {
      //判断当前环境
      if (curEnv(Taro.getEnv()) === "wx") {
        if (props.typeName == "bar") {
          return <React.Suspense fallback={<Loading show></Loading>}>
            <G_Bar {...this.props} />
          </React.Suspense>
        } else if (props.typeName == "pie") {
          return <React.Suspense fallback={<Loading show></Loading>}>
            <G_Pie {...this.props} />
          </React.Suspense>
        } else if (props.typeName == "line") {
          return <React.Suspense fallback={<Loading show></Loading>}>
            <G_Line {...this.props} />
          </React.Suspense>
        } else {
          return <></>
        }
        return <></>
      } else if (curEnv(Taro.getEnv()) === "h5") {
        const typename = xxxxx
        const FormComponent = React.lazy(() => import(`@/components/Form/${typename}`))
        if (FormComponent) {
          return <React.Suspense fallback={<Loading show></Loading>}>
            <FormComponent {...this.props}></FormComponent>
          </React.Suspense>
        }
      }
    }
  }
}

curEnv函数

//判断当前环境
export function curEnv(env) {
  if (!env) {
    return;
  }
  if (env == "WEAPP") {
    //微信小程序
    return 'wx';
  } else if (env == "SWAN") {
    return 'bd';
  } else if (env == "ALIPAY") {
    //支付宝
    return 'zfb';
  } else if (env == "TT") {
    //字节跳动
    return 'zj';
  } else if (env == "WEB") {
    return 'h5';
  } else if (env == "RN") {
    return 'reactNative';
  } else if (env == "QUICKAPP") {
    //快应用
    return 'quickApp';
  } else if (env == "QQ") {
    return 'qq';
  } else if (env == "JD") {
    return 'jd';
  }else{
    return null
  }
}

参考网址:https://docs.taro.zone/en/docs/dynamic-import

欢迎加入前端全栈开发交流圈一起吹水聊天学习交流qq群:837051545

个人网站:沉默小管
如有错误,请多多指教。
如对你有帮助,给个赞吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沉默小管

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值