我正在尝试实现React文档中提到的基于路由的代码拆分。
在添加懒惰实现之前,这是我的应用程序。这很好:
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)
我做错什么了吗?
其他上下文:
如果重要的话,组件被命名为默认重新导出的组件,因为这是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",
以下是GitHub上的源代码和可能的相关问题。
在研究了我自己的问题后,我从依赖关系中找到了答案。我的react
和react-dom
在不同的主要版本上。
这修复了它:npm i -D react-dom@17.0.1
我也遇到了这个问题,结果发现错误是因为我的导入语句周围有括号,这意味着我没有返回任何
const MyComponent = React.lazy(() => {
import('./scenes/MyComponent')
)};
一旦我去掉括号,一切都很顺利,因为我实际上并没有返回什么东西。
const MyComponent = React.lazy(() =>
import('./scenes/MyComponent')
);
解决未捕获的未定义错误同时使用延迟加载
将react和react dom升级到相同版本>=17.0.2
代码应该类似于这个
const Ecg = React.lazy(() => import('../ECG/Ecg'));
<Suspense fallback={<p>Loading...</p>}>
{
devicepage === "Ecg" ?
<Ecg val={egcvalue} devicecall={() => sendMsg('Ecg')}
devicecall1={shiftdata} /> : null
}
</Suspense>