【问题标题】:React loadable not rendering component, only displaying the Loading functionReact loadable 不渲染组件,只显示加载功能
【发布时间】:2019-01-03 18:35:48
【问题描述】:

我正在使用 React Loadable 在显示组件之间显示快速加载消息。但是,在生产中,它不显示组件,只显示“正在加载...”消息。出于某种原因,它在本地工作(localhost:3000),但在实时环境中测试时不会呈现。

这是我到目前为止的代码:

routes.js

// Loading function component
function Loading() {
  return <div>Loading...</div>;
}

const Compose = Loadable({
  loader: () => import('./views/Apps/Email/Compose'),
  loading: Loading,
});

const Inbox = Loadable({
  loader: () => import('./views/Apps/Email/Inbox'),
  loading: Loading,
});

const Message = Loadable({
  loader: () => import('./views/Apps/Email/Message'),
  loading: Loading,
});
.....etc

App.js

function Loading() {
  return <div>Loading...</div>;
};

const DefaultLayout = Loadable({
  loader: () => import('./containers/DefaultLayout'),
  loading: Loading,
});

class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <Switch>
        <Route exact path="/login" name="Login Page" component={Login} />
          <Route exact path="/register" name="Register Page" component={Register} />
          <Route exact path="/404" name="Page 404" component={Page404} />
          <Route exact path="/500" name="Page 500" component={Page500} />
          <Route path="/" name="Home" component={DefaultLayout} />
        </Switch>
      </BrowserRouter>
    );
  }
}

DefaultLayout.js

 <main className="main">
        <AppBreadcrumb appRoutes={routes}/>
        <Container fluid>
          <Switch>
            {routes.map((route, idx) => {
                return route.component ? (<Route key={idx} path={route.path} exact={route.exact} name={route.name} render={props => (
                    <route.component {...props} />
                  )} />)
                  : (null);
              },
            )}
            <Redirect from="/" to="/dashboard"></Redirect>
          </Switch>
        </Container>

还要提一提*,在用户使用 Google OAuth 成功登录后,我会显示这些组件/路由。这是我的重定向:

登录.js

if (postData) {
  PostData('api/v1/zuulusers', postData).then((result) => {
     let responseJson = result;
     localStorage.setItem("userData", JSON.stringify(responseJson));
     this.setState({redirect: true});
  });
  } else {}
}
render() {

  if (this.state.redirect || localStorage.getItem('userData')) {
    return (<Redirect to={'/'}/>)
}

【问题讨论】:

  • 您确定您的生产配置允许您使用代码拆分吗?
  • 我怎么知道它没有?
  • 因为你说它在你的 localhost:3000 上工作。这通常是一个不同的 Webpack 配置。你用过 create-react-app 吗?

标签: javascript reactjs


【解决方案1】:

这是 react-loadable 的问题。不建议将此库与 React 一起使用。由于某种原因,该库无法正确读取块,因为它与 WebPack v4+ 配合不佳,而且该库不再需要维护。要解决这个问题,你应该迁移到 React.lazy(如果你不需要服务器渲染) - https://reactjs.org/docs/code-splitting.html,或者像 @loadable.component 这样的其他库 - https://www.npmjs.com/package/@loadable/component。第二个建议(如果您没有大项目):不缩小代码不是问题,当然这取决于您。

【讨论】:

    猜你喜欢
    • 2021-08-23
    • 2020-01-06
    • 2022-11-29
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 2018-02-17
    • 2017-07-14
    • 2020-03-26
    相关资源
    最近更新 更多