reactjs - 使用 react-router-dom 时延迟加载不起作用
问题描述
尝试了网络上所有可能的解决方案。请帮忙。
- 冉
npm run eject
- 编辑 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
解决方案
我有我的错误。webpack 或 babel 配置与延迟加载无关,除非您使用我不是的 Typescript。我的代码中有语法错误,我的 IDE 无法识别。
而不是这个
<Route
path="/auth"
render={(props) => {
<Auth {...props} />;
}}
/>
应该是这个
<Route path="/auth" render=(props) => <Auth {...props} /> />
推荐阅读
- python - 如何点击热图的正方形来过滤链接的条形图?(牵牛星)
- python - pandas to_datetime 仅转换某些列
- netsuite - 如何自定义 NetSuite 的供应商中心
- reactjs - 在 TypeScript 和 React 中处理函数回调
- swiftui - 使用 `UIViewRepresentable` 来桥接 `UITextView`,它会增长和缩小以使其文本适合 SwiftUI
- flutter - 如何在flutter中将路由更改更新为非root Navigator的浏览器URL?
- java - 如何将 for 循环转换为生产者?
- java - Tomcat从7.0.59升级到8.5.51后JSP编译异常
- docker - 在 Ubuntu 上找不到 Docker 命令
- python - 使用 Python 处理来自 Shell 脚本的返回码