我正在 React 中制作一个单页应用程序,并且我使用 “lazy” 函数和 “Suspense” 组件仅在需要时导入组件。但我有一个奇怪的错误,我不明白它说:
错误:未捕获类型错误:无法将项目转换为字符串
我的代码在App.jsx:
import "./App.css";
import { lazy, Suspense } from "react";
import { Route } from "./Route.jsx";
import { Router } from "./Router.jsx";
const Home = lazy(() => import("./pages/Home.jsx"));
const About = lazy(() => import("./pages/About.jsx"));
const Search = lazy(() => import("./pages/Search.jsx"));
function App() {
return (
<main>
<Suspense fallback={null}>
<Router defaultComponent={() => <h1>404</h1>}>
<Route path="/" Component={Home}></Route>
<Route path="/about" Component={About}></Route>
<Route path="/search/:query" Component={Search}></Route>
</Router>
</Suspense>
</main>
);
}
export default App;
我尝试询问 ChatGPT 并将此问题发布到不和谐服务器中,但他们忽略了我:(
当你使用 lazy 时,你必须像这样使用它,而不是 Route 中的 Component 属性,你必须使用 element 并且元素的值应该像这样
<lazyVariableName/>
import "./App.css";
import { lazy, Suspense } from "react";
import { Route } from "./Route.jsx";
import { Router } from "./Router.jsx";
const Home = lazy(() => import("./pages/Home.jsx"));
const About = lazy(() => import("./pages/About.jsx"));
const Search = lazy(() => import("./pages/Search.jsx"));
function App() {
return (
<main>
<Suspense fallback={null}>
<Router defaultComponent={() => <h1>404</h1>}>
<Route path="/" element={<Home/>}></Route>
<Route path="/about" element={<About/>}></Route>
<Route path="/search/:query" element={<Search/>}></Route>
</Router>
</Suspense>
</main>
);
}
export default App;