Created
April 3, 2018 10:55
-
-
Save rainstormza/b39dd04ed11e6e0025765aefb9ff77eb to your computer and use it in GitHub Desktop.
Code Splitting React js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Dynamically imported components | |
const RegisterPage = asyncComponent(() => | |
import('./register/RegisterPage').then(module => module.default) | |
) | |
const SearchPage = asyncComponent(() => | |
import('./search/SearchPage').then(module => module.default) | |
) | |
const ReportPage = asyncComponent(() => | |
import('./report/ReportPage').then(module => module.default) | |
) | |
<Route path="/" exact render={() => <Redirect to="/register" />} /> | |
<Route path="/register" component={Routes.RegisterPage} /> | |
<Route path="/search" component={Routes.SearchPage} /> | |
<Route path="/report" component={Routes.ReportPage} /> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from "react"; | |
export default function asyncComponent(getComponent) { | |
class AsyncComponent extends Component { | |
static Component = null; | |
state = { Component: AsyncComponent.Component }; | |
componentWillMount() { | |
if (!this.state.Component) { | |
getComponent().then(Component => { | |
AsyncComponent.Component = Component | |
this.setState({ Component }) | |
}) | |
} | |
} | |
render() { | |
const { Component } = this.state | |
if (Component) { | |
return <Component {...this.props} /> | |
} | |
return null | |
} | |
} | |
return AsyncComponent; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment