简体   繁体   中英

How to lazy load components to React router dom Route component?

I have this:

<Router>
  <Route component={MyLazyLoadedComponent} />
</Router>

I thought about doing:

<Router>
  <Route render={props => {
    import('path/to/component').then(Module => {
      return <Module.default {...props.match.params} />
    })
  }} />
</Router/>

But this ain't working since <Route /> component from the React router Dom isn't async (route is actually rendered BEFORE the import). How to achieve this code splitting?

The question actually also relevant for Webpack as well as Parcel bundler.

I think this should work:

const AsyncComponent = React.lazy(() => import('path/of/component'));

...

 <Route path={`path`} render={props => <AsyncComponent {...props} />} />

...

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM