【问题标题】:Lazy loading doesn't work when using react-router-dom使用 react-router-dom 时延迟加载不起作用
【发布时间】:2021-04-25 03:11:00
【问题描述】:

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

  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

【问题讨论】:

    标签: reactjs webpack lazy-loading react-router-dom


    【解决方案1】:

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

    不是这个

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

    应该是这样的

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

    【讨论】:

      猜你喜欢
      • 2019-07-25
      • 2021-12-25
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 2019-01-18
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      相关资源
      最近更新 更多