国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

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

2019-11-19 12:19:13
字體:
來源:轉載
供稿:網友

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>)

三:預覽效果

可以看到有一個警告,內容是

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 会东县| 合江县| 思南县| 张家界市| 中牟县| 桓台县| 武冈市| 北票市| 宽甸| 东平县| 绩溪县| 永寿县| 广昌县| 甘泉县| 东光县| 晋江市| 横山县| 明光市| 习水县| 金华市| 孟津县| 九台市| 东丰县| 叶城县| 当雄县| 桐梓县| 武义县| 定襄县| 宜兰市| 桑日县| 虎林市| 军事| 临泉县| 防城港市| 平舆县| 镇宁| 油尖旺区| 武义县| 鄂托克前旗| 宜兰市| 珠海市|