我正在使用 React 和 React-Router 构建 SPA(单页应用程序)。“员工”是标题中的导航菜单项之一。根据文档-基于路由的代码拆分,我正在尝试像这样使组件延迟加载:
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>
)
};
问题是 - 单击“员工”导航项时,网页变为空白。我究竟做错了什么?
警告:懒惰:预期动态 import() 调用的结果。而是收到: [object Module] 您的代码应如下所示: const MyComponent = lazy(() => import('./MyComponent'))