您的当前位置:首页react-router4按需加载(踩坑填坑)

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

2020-11-27 来源:乌哈旅游

这个警告其实是在组件卸载的时候执行了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

显示全文