我正在使用React和React-Router构建SPA(单页应用程序)。 “雇员”是标题中的导航菜单项之一。 根据文档-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>
)
};
问题是-单击“雇员”导航项时,网页变为空白。我在做什么错了?
警告:懒惰:期望动态import()调用的结果。而是收到:[对象模块] 您的代码应如下所示: const MyComponent = lazy(()=> import('./ MyComponent'))
答案 0 :(得分:1)
这是说它希望“雇员”组件是文件的默认导出。您必须将其更改为默认导出:https://reactjs.org/docs/code-splitting.html#named-exports
答案 1 :(得分:0)
两件事。
render
),使用component
道具代替Router
。Suspense
(而不是整个Employees
(在您的Switch
道具内)包装在render
中。