react-router4按需加载(踩坑填坑)
网络编程 2021-07-04 15:49www.168986.cn编程入门
这篇文章主要介绍了react-router4按需加载(踩坑填坑),长沙网络推广觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随长沙网络推广过来看看吧
react-router4如何去实现按需加载Component,在router4以前,我们是使用getComponent的方式来实现按需加载的,router4中,getComponent方法已经被移除,网上有好几种方案大多都解决的不太彻底,狼蚁网站SEO优化我说一下我的方案:
一:创建asyncComponent.js
import React, { Component } from "react"; export default function asyncComponent(importComponent) { class AsyncComponent extends Component { constructor(props) { super(props); this.state = { ponent: null }; } async ponentDidMount() { if(this.hasLoadedComponent()){ return; } const { default: ponent } = await importComponent(); this.setState({ ponent: ponent }); } hasLoadedComponent() { return this.state.ponent !== null; } render() { const C = this.state.ponent; 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="/" ponent={Home} /> <Route exact path="/about" ponent={About} /> <Redirect to="/" /> </Switch> </BrowserRouter> )
三:预览效果
可以看到有一个警告,内容是
Warning: Can't perform a React state update on an unmounted ponent. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the ponentWillUnmount method
这个警告其实是在组件卸载的时候执行了setState,虽然这个警告并不影响正常使用,但是看着总是不爽,所以我们要在组件卸载的时候结束setState,如下:
ponentWillUnmount(){ 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 = { ponent: null }; } async ponentDidMount() { if(this.hasLoadedComponent()){ return; } const { default: ponent } = await importComponent(); this.setState({ ponent: ponent }); } hasLoadedComponent() { return this.state.ponent !== null; } ponentWillUnmount(){ this.setState = (state,callback)=>{ return } } render() { const C = this.state.ponent; 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开源项目:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持狼蚁SEO。
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程