javascript - 元素类型无效。需要一个字符串,发现未定义
问题描述
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
到 version10.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>
</>
);
}
推荐阅读
- linux - 如何通过 bash 脚本使用 netcat 获取 http 状态码
- android - 在edittext中打开键盘时Android滚动视图不起作用
- python - 如何使用 soup.find_all() 提供以 sometext 开头的 attrs
- javascript - 通过公共值js映射两个对象数组
- r - 如何获得每列的中位数和标准差?
- flutter - 我如何处理未来不返回?
- reactjs - Redux 商店中的多对多关系
- python - 如何在 MATLAB、Python 和 C 中有效地计算大的复数值?
- google-cloud-functions - pdfmake节点js库中的Google Cloud函数本地目录图像读取错误
- django - 使用 Grappelli 扩展时更改表单中的 Django Admin 模型千位分隔符