网站搜索

reactjs - Recoil Nexus - 元素类型无效:预期为字符串(用于内置组件)或类/函数(用于复合组件),但得到的是对象


我开始收到错误:

error - Error: Element type is invalid: expected a string (for built-in components) or
               a class/function (for composite components) but got: object.
               at ReactDOMServerRenderer.render ...

在为我的 NextJS 项目添加 TypeScript 支持时。

我搜索了类似的问题,但答案大多是关于错误的导入/导出。但在我的情况下,似乎不是那个问题。

在这个错误发生之前,我也会收到一个警告:

Warning: React.jsx: type is invalid -- expected a string (for built-in components) or
a class/function (for composite components) but got: object.

Check your code at _app.js:18.
    at App (webpack-internal:///./pages/_app.js:19:16)

这是我的 _app.js:

import "../styles/global.scss";
import "video.js/dist/video-js.css";
import { RecoilRoot } from "recoil";
import RecoilNexus from "recoil-nexus";
import { CookiesProvider } from "react-cookie";
import Head from "next/head";

export default function App({ Component, pageProps }) {

  return (
    <>
      <Head>
        <meta name="theme-color" content="#fff" />
        <meta name="viewport" content="initial-scale=1, width=device-width" />
      </Head>
      <CookiesProvider>
        <RecoilRoot>
          <RecoilNexus />
          <Component {...pageProps} />
        </RecoilRoot>
      </CookiesProvider>
    </>
  );
}

所以错误是由于 <RecoilNexus /> 部分产生的。

我尝试把它注释掉,错误就消失了。然而,我仍然需要在我的项目中使用它。

答案#1

仅仅将我的 _app.js 文件的扩展名更改为 _app.tsx 就解决了问题。我仍然不确定为什么会发生这种情况,也不清楚这个问题是否只在使用 recoil-nexus 并向 NextJS 项目中添加 TS 时才会出现,还是在将 TS 添加到现有项目时都需要这样做。我很乐意了解更多关于这一情况的原因。