延迟加载 ReactJS 组件

Lazy loading ReactJS component

我正在使用 React 和 React-Router 构建 SPA(单页应用程序)。 “员工”是 header 中的导航菜单项之一。 根据文档 - Route-based code splitting,我正在尝试像这样使组件延迟加载:

import React, { Component, lazy, Suspense } from 'react';
import './App.css';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
...
// import { Employees } from './components/Employees/Employees';
const Employees = lazy(() => import('./components/Employees/Employees'));

export default class App extends Component {
  state = {
    ...
    employeesData: [
        ...objects with data...
    ]
  }

  render() {
    return (
      <BrowserRouter>
        <div className="App">
          ...
          <Suspense fallback={<div>Loading...</div>}>
          <Switch>
        
            {/* other routes here */}
           
            <Route path="/employees/" component={
              () =>
                <Employees
                  data={this.state.employeesData}
                />
            } />

          </Switch>
          </Suspense>
          ...
        </div>
      </BrowserRouter>
    );
  }
}

Employees 组件看起来像:

import React from 'react';
import './css/Employees.css';

export const Employees = (props) => {

    const { data } = { ...props };

    // sort elements by name value
    data.sort(
        (a,b) => (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0)
    );

    let items = [];    
    
    for (let i = 0; i < data.length; i++) { 
        items.push(
            <div className="container">
                <div className="imgbox">
                    <img className="image"
                        src={ data[i].image }
                        alt={ data[i].name }                        
                    />                    
                </div>
                <div className="textbox">
                    <h4 className="name">
                        { data[i].name }
                    </h4>
                    <p className="text">
                        { data[i].title }
                        <br/>
                        { data[i].text }
                        <br/>
                        { data[i].workplace }                            
                    </p>
                </div>
            </div>
        );
    }

    return (
        <div className="Employees">
            ...

            <div className="wrapper">
                ...

                { items }

            </div>
        </div>
    )
};

问题是 - 单击“员工”导航项时,web-page 变为空白。我做错了什么?

Warning: lazy: Expected the result of a dynamic import() call. Instead received: [object Module] Your code should look like: const MyComponent = lazy(() => import('./MyComponent'))

两件事。

  1. 在这种情况下使用 render 道具而不是 component (Router)。
  2. 只在 Suspense 中包裹你的 Employees 而不是整个 Switch(在你的 render 道具中)。

这是说它希望 Employees 组件成为文件的默认导出。您必须将其更改为默认导出:https://reactjs.org/docs/code-splitting.html#named-exports