React.lazy错误Object(...)不是函数

时间:2018-11-04 18:56:51

标签: javascript reactjs react-router

我正在尝试延迟加载App组件。我已经阅读了React文档样本,并提出了以下解决方案。但是,我得到了TypeError: Object(...) is not a function,但不确定为什么。我也尝试过做import('').default

import React, { lazy, Suspense } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

// import { App } from './components/navigation';
// import Login from './components/login/LoginContainer';
import PrivateRoute from './components/privateRoute/PrivateRoute';
import HTML5Backend from 'react-dnd-html5-backend';
import { DragDropContext } from 'react-dnd';
import { Redirect } from 'react-router';

const Login = lazy(() => import('./components/login/LoginContainer'));
const App = lazy(() => import('./components/navigation/AppContainer'));

const Main = () => {
  return (
    <BrowserRouter>
      <Suspense fallback={<div>Loading...</div>}>
        <Switch>
          <Route name="login" exact path="/login" component={Login} />
          <Route name="loginWithTripId" exact path="/login/:tripid" component={Login} />
          <PrivateRoute path="/trips/:tripid" component={App} />
          <PrivateRoute path="/trips/dashboard" component={App} />
          <Route render={() => <Redirect to={'/login'} />} />
        </Switch>
      </Suspense>
    </BrowserRouter>
  );
};

export default DragDropContext(HTML5Backend)(Main);

由于某种原因,如果我将console.log记录下来,React.lazy是undefined ...我试图删除node_modules并再次执行npm install却没有成功

3 个答案:

答案 0 :(得分:1)

检查您的React版本,懒惰是在16.6中引入的

https://reactjs.org/blog/2018/10/23/react-v-16-6.html

答案 1 :(得分:0)

好,因此我设法通过关闭开发服务器并使用npm start重新启动来解决此问题。

答案 2 :(得分:0)

在开发服务器中,例如,使用webpack-dev-server,您必须使用:

const Login = lazy(() => import('./components/navigation/LoginContainer')); ... <Route name="login" exact path="/login" component={props => <Login {...props} />} /> ...

它也将在生产环境中工作。