欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

react-router4按需加载(踩坑填坑)

程序员文章站 2022-03-30 22:30:21
react-router4如何去实现按需加载component,在router4以前,我们是使用getcomponent的方式来实现按需加载的,router4中,getco...

react-router4如何去实现按需加载component,在router4以前,我们是使用getcomponent的方式来实现按需加载的,router4中,getcomponent方法已经被移除,网上有好几种方案大多都解决的不太彻底,下面我说一下我的方案:

一:创建asynccomponent.js

import react, { component } from "react";

export default function asynccomponent(importcomponent) {
 class asynccomponent extends component {
 constructor(props) {
  super(props);

  this.state = {
  component: null
  };
 }

 async componentdidmount() {
  if(this.hasloadedcomponent()){
   return;
  }
  const { default: component } = await importcomponent();
  this.setstate({
  component: component
  });
 }

 hasloadedcomponent() {
  return this.state.component !== null;
 }
 
 render() {
  const c = this.state.component;

  return c ? <c {...this.props} /> : null;
 }
 }

 return asynccomponent;
}

二:在引入asynccomponent.js,并导入需要按需加载的模块

 import asynccomponent from "utils/asynccomponent"

 const home = asynccomponent(() => import("./home"))
 const about = asynccomponent(() => import("./about"))

二:render部分

 const routes = () => (
 <browserrouter>
  <switch>
   <route exact path="/" component={home} />
   <route exact path="/about" component={about} />
   <redirect to="/" />
  </switch>
 </browserrouter>
)

三:预览效果

react-router4按需加载(踩坑填坑)

可以看到有一个警告,内容是

warning: can't perform a react state update on an unmounted component. this is a no-op, but it indicates a memory leak in your application. to fix, cancel all subscriptions and asynchronous tasks in the componentwillunmount method

这个警告其实是在组件卸载的时候执行了setstate,虽然这个警告并不影响正常使用,但是看着总是不爽,所以我们要在组件卸载的时候结束setstate,如下:

componentwillunmount(){
 this.setstate = (state,callback)=>{
  return
  }
}

四:完整版asynccomponent.js

import react, { component } from "react";

export default function asynccomponent(importcomponent) {
 class asynccomponent extends component {
 constructor(props) {
  super(props);

  this.state = {
  component: null
  };
 }

 async componentdidmount() {
  if(this.hasloadedcomponent()){
   return;
  }
  const { default: component } = await importcomponent();
  this.setstate({
  component: component
  });
 }

 hasloadedcomponent() {
  return this.state.component !== null;
 }
 componentwillunmount(){
  this.setstate = (state,callback)=>{
  return
  }
 }

 render() {
  const c = this.state.component;

  return c ? <c {...this.props} /> : null;
 }
 }

 return asynccomponent;
}

五: webpack部分配置需要配置chunkfilename

eturn {
 output: {
  path: path.resolve(cwd, config.build),
  publicpath: config.static[process.env.mode],
  chunkfilename: 'js/[name]-[chunkhash:8].js',
  filename: 'js/[name].js',
 },

结尾推广一下我的react-native开源项目:https://github.com/duheng/mozi

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。