网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

react-router4怎么实现按需加载

这篇文章给大家分享的是有关react-router4怎么实现按需加载的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

江夏ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18982081108(备注:SSL证书合作)期待与您的合作!

一:创建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 ?  : null;
 }
 }

 return AsyncComponent;
}

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

 import asyncComponent from "utils/asyncComponent"

 const Home = asyncComponent(() => import("./home"))
 const About = asyncComponent(() => import("./about"))

二:render部分

 const routes = () => (
 
  
   
   
   
  
 
)

三:预览效果

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 ?  : 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-router4怎么实现按需加载”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!


标题名称:react-router4怎么实现按需加载
URL网址:http://bjjierui.cn/article/gisepj.html

其他资讯