React Router Lazy Component无法正常工作 [英] React Router Lazy Component isn't working

查看:561
本文介绍了React Router Lazy Component无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可行:

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.6React Router 5.0.0

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

有人可以看到我在这里做什么愚蠢的事情吗?

Can anyone see what stupid thing I am doing here?

推荐答案

引用 与代码拆分相关的文档 ,建议您将 Suspense 与已定义的 fallback 结合使用,这样您就可以在尚未加载的组件上进行渲染.

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

暂记应该是使用 lazy

这篇关于React Router Lazy Component无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆