使用React.lazy时未捕获未定义的错误 [英] Uncaught undefined error when using React.lazy
本文介绍了使用React.lazy时未捕获未定义的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试实现Reaction文档中提到的Route-based code splitting。
在添加延迟实现之前,这是我的应用程序。此功能运行正常:
import Counter from "./Counter";
import Home from "./Home";
import Login from "./Login";
export function App() {
return (
<Router>
<Suspense fallback={<div>"Loading.."</div>}>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/login" component={Login} />
<Route exact path="/counter" component={Counter} />
</Switch>
</Router>
);
}
我所做的更改只是将3个导入替换为:
import { lazy, Suspense } from "react";
const Home = lazy(() => import("./Home"));
const Login = lazy(() => import("./Login"));
const Counter = lazy(() => import("./Counter"));
此代码成功构建,但浏览器上没有呈现任何内容,并且我在控制台中收到以下错误:
Uncaught undefined
The above error occurred in one of your React components:
in Unknown (created by Context.Consumer)
in Route (at App.tsx:29)
in Switch (at App.tsx:28)
in Suspense (at App.tsx:27)
in Router (created by BrowserRouter)
in BrowserRouter (at App.tsx:25)
in ErrorBoundary (at App.tsx:24)
in App (at src/index.tsx:19)
in Provider (at src/index.tsx:18)
in StrictMode (at src/index.tsx:17)
我做错了什么吗?
其他上下文:
如果重要,这些组件将被命名为Components,默认情况下会重新导出,因为这是React.lazy:
所必需的export { Home as default } from "./Home";
其中一个组件使用redux,因此应用程序被包装在商店提供程序中:
<Provider store={store}>
<App />
</Provider>
这是我的tsconfig:
{
"compilerOptions": {
"baseUrl": ".",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"noFallthroughCasesInSwitch": true,
"target": "es5",
"module": "esnext"
},
"include": [
"src"
]
}
和包版本:
"react": "^17.0.1",
"react-dom": "^16.13.1",
"react-redux": "^7.2.1",
"react-scripts": "^4.0.1",
"react-router-dom": "^5.2.0",
"typescript": "^4.1.2",
这里是source code,可能与issue on GitHub相关。
推荐答案
在查看了我自己的问题后,我通过查看依赖项找到了答案。我的react
和react-dom
位于不同的主要版本上。
此操作已修复:
npm i -D react-dom@17.0.1
这篇关于使用React.lazy时未捕获未定义的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文