代码之家  ›  专栏  ›  技术社区  ›  Adam Jenkins

反应路由器惰性组件

  •  1
  • Adam Jenkins  · 技术社区  · 5 年前

    所以这是可行的:

    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路由器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
    

    1 回复  |  直到 3 年前
        1
  •  11
  •   John Ruddell    5 年前

    参考 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> lazy

        2
  •  2
  •   Adrian Guerrero    3 年前

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