反应路线四如何去实现按需加载组件,在router4以前,我们是使用类名的方式来实现按需加载的,router4中,getComponent方法已经被移除,网上有好几种方案大多都解决的不太彻底,下面我说一下我的方案:
一:创建asyncComponent.js
从"反应"导入反应{组件};导出默认函数异步组件(导入组件){类异步组件扩展组件{构造函数(道具){ super(道具)};这个。状态={组件: null };} async ComponentDidMount(){ if(this。HasLoadComponent()){ return;} const {默认:组件}=wait import component();这个。setstate({ component : component });} HasLoadComponent(){ 0返回this.state.component!==null} render(){ const C=this。国家。组件;返回c?C {.这个。props }/: null;} }返回AsyncComponent}二:在引入asyncComponent.js,并导入需要按需加载的模块
从“utils/asyncComponent”常量Home=异步组件(()=导入(')导入异步组件./home’)常量About=asyncComponent(()=import(' ./about '))二:渲染部分
常量路由=()=(浏览器外部交换机路由精确路径='/'组件={主目录} /路由精确路径='/关于'组件={关于} /重定向到='/'//交换机/浏览器外部)三:预览效果
可以看到有一个警告,内容是
警告:无法对卸载的组件执行反应状态更新。这是一个没有行动,但它表明您的应用程序内存泄漏。要解决此问题,请取消组件卸载方法中的所有订阅和异步任务
这个警告其实是在组件卸载的时候执行了setState,虽然这个警告并不影响正常使用,但是看着总是不爽,所以我们要在组件卸载的时候结束setState,如下:
组件将卸载(){ this。SetState=(状态,回调)={ return }四:完整版asyncComponent.js
从"反应"导入反应{组件};导出默认函数异步组件(导入组件){类异步组件扩展组件{构造函数(道具){ super(道具)};这个。状态={组件: null };} async ComponentDidMount(){ if(this。HasLoadComponent()){ return;} const {默认:组件}=wait import component();这个。setstate({ component : component });} HasLoadComponent(){ 0返回this.state.component!==null } componentWillunmount(){ this。SetState=(state,callback)={ return } } render(){ const C=this。国家。组件;返回c?C {.这个。props }/: null;} }返回AsyncComponent}五:webpack部分配置需要配置组块文件名
eturn { output : { path : path。解析(CWD,配置.构建),公共路径:配置。静态[过程。环境。模式],chunk filename : ' js/[name]-[chunk hash 33608].js ',filename: 'js/[name].js ',},结尾推广一下我的反应原生开源项目:https://github。com/杜衡/墨子
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。