1
0
mirror of https://github.com/SomboChea/ui synced 2024-11-24 06:54:27 +07:00

feat: use React.lazy for loading components (#158)

This commit is contained in:
Antoine Chalifour 2019-10-05 20:13:36 +02:00 committed by Juan Picado @jotadeveloper
parent f1f8f8ae3f
commit a365ec548a
2 changed files with 5 additions and 40 deletions

View File

@ -5,16 +5,15 @@ import { Router, Route, Switch } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import { AppContextConsumer, AppStateInterface } from './App/App';
import { asyncComponent } from './utils/asyncComponent';
import Header from './components/Header';
const history = createBrowserHistory({
basename: window.__VERDACCIO_BASENAME_UI_OPTIONS && window.__VERDACCIO_BASENAME_UI_OPTIONS.url_prefix,
});
const NotFound = asyncComponent(() => import('./components/NotFound'));
const VersionPackage = asyncComponent(() => import('./pages/Version'));
const HomePage = asyncComponent(() => import('./pages/home'));
const NotFound = React.lazy(() => import('./components/NotFound'));
const VersionPackage = React.lazy(() => import('./pages/Version'));
const HomePage = React.lazy(() => import('./pages/home'));
interface RouterAppProps {
onLogout: () => void;
@ -25,7 +24,7 @@ class RouterApp extends Component<RouterAppProps> {
public render(): ReactElement<HTMLDivElement> {
return (
<Router history={history}>
<>
<React.Suspense fallback={null}>
{this.renderHeader()}
<Switch>
<Route exact={true} path={'/'} render={this.renderHomePage} />
@ -35,7 +34,7 @@ class RouterApp extends Component<RouterAppProps> {
<Route exact={true} path={'/-/web/detail/@:scope/:package/v/:version'} render={this.renderVersionPage} />
<Route component={NotFound} />
</Switch>
</>
</React.Suspense>
</Router>
);
}

View File

@ -1,34 +0,0 @@
import React, { ComponentClass } from 'react';
export function asyncComponent(getComponent): ComponentClass {
return class AsyncComponent extends React.Component {
public static Component = null;
public state = { Component: AsyncComponent.Component };
public componentDidMount(): void {
const { Component } = this.state;
if (!Component) {
getComponent()
.then(({ default: Component }) => {
AsyncComponent.Component = Component;
/* eslint react/no-did-mount-set-state:0 */
this.setState({ Component });
})
.catch(err => {
console.error(err);
});
}
}
public render(): JSX.Element | null {
const { Component } = this.state;
if (Component) {
// eslint-disable-next-line verdaccio/jsx-spread
// @ts-ignore
return <Component {...this.props} />;
}
return null;
}
};
}