问题描述
公司项目需要动态加载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
个人网站:沉默小管
如有错误,请多多指教。
如对你有帮助,给个赞吧。