React学习(五)- Route路由的懒加载

一.前言

  懒加载也有其它叫法,比如按需加载,代码分页等。简单来说,就是将js代码分割成多个文件,根据需要再加载对应js文件。

  在单页面应用中,我们可以使用懒加载,根据不同的路由去加载对应页面的js文件。这样可以减少首屏加载时间,同时减少资源浪费。

二.使用React-Route

  参考我之前的文章,有讲React-Route的使用,下面用的是v4版本。

三.安装懒加载包

npm install react-loadable --save

 四.使用

  引用react-loadable。

import Loadable from 'react-loadable';

  使用loadable的方法。这个是懒加载方法。配合webpack会自动将其引用的组件切割到单独的js文件中。loader是引用组件。loading是初次加载组件所调用的回调方法。

const AsyncTab1 = Loadable({
    loader: () => import('./component/Tab1.jsx'),
    loading: MyLoadingComponent
});
const AsyncTab2 = Loadable({
    loader: () => import('./component/Tab2.jsx'),
    loading: MyLoadingComponent
});
const AsyncTab3 = Loadable({
    loader: () => import('./component/Tab3.jsx'),
    loading: MyLoadingComponent
});

const MyLoadingComponent = ({ isLoading, error }) => {
    // Handle the loading state
    if (isLoading) {
        return <div>Loading...</div>;
    }
    // Handle the error state
    else if (error) {
        return <div>Sorry, there was a problem loading the page.</div>;
    }
    else {
        return null;
    }
};

  配合Route路由来调用。

render() {
    return <Router>
        <Home>
            <Route path="/" component={AsyncTab1} />
            <Route path="/tab2" component={AsyncTab2} />
            <Route path="/tab3" component={AsyncTab3} />
        </Home>

    </Router>;
}

  通过webpack打包后,会自动将它切割为多份js文件,在页面切换路由,才加载对应js。

五.题外话

  使用这个loadable这个插件,在浏览器上可能会出现下面的提示信息。

  componentWillMount has been renamed, and is not recommended for use.

  这是在React的v17版本中,componentWillMount这个生命周期方法被视为不安全,已经重命名了。仍然引用旧名称,会提示错误信息。loadable这个组件就使用旧的生命周期方法,目前也没有版本更新。

  可以手动去node_modules文件夹,将这个loadable组件中使用componentWillMount方法的地方替换成UNSAFE_componentWillMount,就不再有这个提示信息。

  

原文地址:https://www.cnblogs.com/shadoll/p/15060428.html