react-router延迟组件不起作用

IT技术 reactjs react-router lazy-loading
2021-05-13 22:39:00

所以这有效:

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}/>}/>
   );
}

react 16.8.6 react-router 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

谁能看到我在这里做什么愚蠢的事情?

2个回答

参考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 应该是<Route>使用元素的父级lazy

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