首页 > 解决方案 > 使用 react-router-dom 时延迟加载不起作用

问题描述

尝试了网络上所有可能的解决方案。请帮忙。

  1. npm run eject
  2. 编辑 package.json 文件并尝试按照https://reactrouter.com/web/guides/code-splitting添加以下代码的推荐解决方案。
  "babel": {
    "presets": [
      "@babel/preset-react"
    ],
    "plugins": [
      "@babel/plugin-syntax-dynamic-import"
    ]
  }

下面是我使用延迟加载的代码。只有根路由(“/”)被加载。当我访问localhost:3000/auth时没有加载任何内容

在此处输入图像描述

import React, { useEffect, Suspense } from 'react';
import { connect } from 'react-redux';
import { Redirect, Route, Switch, withRouter } from 'react-router-dom';

import Layout from './components/Layout/Layout';
import Logout from './containers/Auth/Logout/Logout';
import BurgerBuilder from './containers/BurgerBuilder/BurgerBuilder';
import * as actions from './store/actions/index';

const Checkout = React.lazy(() => import('./containers/Checkout/Checkout'));
const Orders = React.lazy(() => import('./containers/Orders/Orders'));
const Auth = React.lazy(() => import('./containers/Auth/Auth'));

const App = (props) => {
  useEffect(() => {
    props.onTryAutoSignup();
  }, []);

  let routes = (
    <Switch>
      <Route
        path="/auth"
        render={(props) => {
          <Auth {...props} />;
        }}
      />
      <Route path="/" exact component={BurgerBuilder} />
      <Redirect to="/" />
    </Switch>
  );
  if (props.isAuthenticated) {
    routes = (
      <Switch>
        <Route path="/checkout" render={(props) => <Checkout {...props} />} />
        <Route path="/orders" render={(props) => <Orders {...props} />} />
        <Route path="/logout" component={Logout} />
        <Route path="/auth" render={(props) => <Auth {...props} />} />
        <Route path="/" exact component={BurgerBuilder} />
        <Redirect to="/" />
      </Switch>
    );
  }
  return (
    <div>
      <Layout>
        <Suspense fallback={<p>Loading...</p>}>{routes}</Suspense>
      </Layout>
    </div>
  );
};

const mapStateToProps = (state) => {
  return {
    isAuthenticated: state.auth.token !== null,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    onTryAutoSignup: () => dispatch(actions.authCheckState()),
  };
};

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));

我的 package.json 文件package.json
我的 webpack 配置文件webpack.config.js

标签: reactjswebpacklazy-loadingreact-router-dom

解决方案


我有我的错误。webpack 或 babel 配置与延迟加载无关,除非您使用我不是的 Typescript。我的代码中有语法错误,我的 IDE 无法识别。

而不是这个

<Route
        path="/auth"
        render={(props) => {
          <Auth {...props} />;
        }}
 />
        

应该是这个

<Route path="/auth" render=(props) => <Auth {...props} /> />

推荐阅读