我正在构建一个Next.js项目,并收到以下错误:
错误:元素类型无效:应为字符串(对于内置组件)或类/函数(对于复合组件),但得到:您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。
当尝试将布局组件导入my_app. js时,出现上述错误。
- _应用程序. js*
import React from "react";
import "@/styles/globals.css";
import Layout from "@/components";
export default function App({ Component, pageProps }) {
return (
<Layout>
<Component {...pageProps} />
</Layout>
);
}
- 布局. jsx**
import Head from "next/head";
import React from "react";
import { Navbar } from "./Navbar";
import { Footer } from "./Footer";
const Layout = () => {
return (
<div className="layout">
<Head>
<title>Ecommerce Store</title>
</Head>
<header>
<Navbar />
</header>
<main className="main-container">empty</main>
<footer>
<Footer />
</footer>
</div>
);
};
export default Layout;
- index. js**-我创建了这个文件来导出所有组件
export { default as Footer } from "./Footer";
export { default as Layout } from "./Layout";
export { default as Navbar } from "./Navbar";
export { default as Product } from "./Product";
export { default as HeroBanner } from "./HeroBanner";
export { default as FooterBanner } from "./FooterBanner";
export { default as Cart } from "./Cart";
零部件文件夹结构
我找到了类似的解决方案,但都无济于事。
(React) Element type is invalid, expected a string (for built-in components) or a class/function but got
Next Js Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined
2条答案
按热度按时间brccelvz1#
正如错误消息所说,我认为您忘记导出某个组件。我看到您正确导出了布局。您在导航栏和页脚组件中也这样做了吗?
lmvvr0a82#
这个错误是在布局组件中,用大括号导入导航栏和页脚。当我们没有将一个组件导出为默认导出,而是尝试将其导入为命名导入(用大括号括起来),或者反之亦然,因为这是导致错误的常见原因。
从位于同一目录的文件导入。如果需要从上一个目录导入,我们可以: