如何解决元素类型无效需要一个字符串,发现未定义
此事件发生在 next-auth
更新之后。突然就抛出这个错误:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in,or you might have mixed up default and named imports.
Check the render method of `MyApp`.
所以我检查了 MyApp 文件,但它似乎没有任何问题,至少我没有看到任何问题。
_app.tsx(next.js 中的 _app 文件)
import React from "react";
import { start,done } from "nprogress";
import "nprogress/nprogress.css";
import router from "next/router";
import "./styles/patch.css";
import { Provider } from "next-auth/client";
import { ApolloProvider } from "@apollo/client";
import { useApollo } from "../apollo/apolloClient";
router.events.on("routeChangeStart",() => start());
router.events.on("routeChangeComplete",() => done());
router.events.on("routeChangeError",() => done());
const MyApp = ({ Component,pageProps }) => {
const apolloClient = useApollo(pageProps.initialApolloState);
React.useEffect(() => {
// Remove the server-side injected CSS.
const jssStyles = document.querySelector("#jss-server-side");
if (jssStyles) {
jssStyles.parentElement.removeChild(jssStyles);
}
},[]);
return (
<ApolloProvider client={apolloClient}>
<Provider session={pageProps.session}>
<Component {...pageProps} />
</Provider>
</ApolloProvider>
);
};
export default MyApp;
我是否遗漏了可能导致此错误的内容?
编辑:
显然,当我使用 webpack 4 时还好。它在使用 webpack 5 时抛出了这个错误。但是如果有 webpack 5 的解决方案就好了。
编辑 2:
当我将 next
更新到版本 10.2
时,它运行得非常好。可能是我做事太仓促了,所以我想一开始没有任何问题。除此之外,我很欣赏这里的答案。
解决方法
不要使用这样的查询:
React.useEffect(() => {
// this is wrong !!!
const jssStyles = document.querySelector("#jss-server-side");
if (jssStyles) {
jssStyles.parentElement.removeChild(jssStyles);
}
},[])
尝试使用 useRef 钩子代替例如:
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。