這篇文章給大家分享的是有關(guān)react-router4怎么實(shí)現(xiàn)按需加載的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
江夏ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場景,ssl證書未來市場廣闊!成為創(chuàng)新互聯(lián)的ssl證書銷售渠道,可以享受市場價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18982081108(備注:SSL證書合作)期待與您的合作!
一:創(chuàng)建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,并導(dǎo)入需要按需加載的模塊
import asyncComponent from "utils/asyncComponent" const Home = asyncComponent(() => import("./home")) const About = asyncComponent(() => import("./about"))
二:render部分
const routes = () => ()
三:預(yù)覽效果
可以看到有一個(gè)警告,內(nèi)容是
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
這個(gè)警告其實(shí)是在組件卸載的時(shí)候執(zhí)行了setState,雖然這個(gè)警告并不影響正常使用,但是看著總是不爽,所以我們要在組件卸載的時(shí)候結(jié)束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', },
感謝各位的閱讀!關(guān)于“react-router4怎么實(shí)現(xiàn)按需加載”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!