react router lazy component

元气小坏坏 提交于 2020-01-04 02:15:10

问题


So this works:

import Page from 'components/Page';
...

render() {
   return (
     <Route render={props => <Page {...props}/>}/>
   );
}

But this doesn't:

import React, { lazy } from 'react';
const Cmp = lazy(() => import('components/Page'));
...

render() {
   return (
     <Route render={props => <Cmp {...props}/>}/>
   );
}

React 16.8.6 React Router 5.0.0

I get this:

The above error occurred in one of your React components:
    in Unknown (at configured.route.js:41)
    in Route (at configured.route.js:41)
    in ConfiguredRoute (created by Context.Consumer)
    ...rest of stack trace

Can anyone see what stupid thing I am doing here?


回答1:


Referencing the React Docs on code splitting, the recommendation is to use Suspense with a defined fallback so you have something to render in place of the components when they haven't loaded.

// Direct paste from https://reactjs.org/docs/code-splitting.html

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import React, { Suspense, lazy } from 'react';

const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));

const App = () => (
  <Router>
    <Suspense fallback={<div>Loading...</div>}>
      <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/about" component={About}/>
      </Switch>
    </Suspense>
  </Router>
);

Suspense should be a parent of the <Route> elements that use lazy



来源:https://stackoverflow.com/questions/56247555/react-router-lazy-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!