React Router 惰性组件不工作

React Router Lazy Component isn't working

所以这有效:

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

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

但事实并非如此:

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

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

反应 16.8.6 反应路由器 5.0.0

我明白了:

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

谁能看到我在做什么蠢事?

参考 React Docs on code splitting,建议将 Suspense 与已定义的 fallback 一起使用,这样当组件尚未加载时,您可以渲染一些东西来代替组件。

// 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 应该是使用 lazy

<Route> 元素的父元素

我更新了 react 的版本并且开始出现这个错误,因为我忘记了也更新 react-dom 包版本,一旦我这样做一切正常。