反应路由器惰性组件

时间:2019-05-21 23:37:45

标签: reactjs react-router lazy-loading

这可行:

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 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 个答案:

答案 0 :(得分:3)

参考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>
);

挂起应该是使用<Route>的{​​{1}}元素的父对象

答案 1 :(得分:1)

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