简体   繁体   English

Typescript 错误与 NextJS 和上下文 API

[英]Typescript error with NextJS and Context API

I have the following code in my _app.tsx file:我的 _app.tsx 文件中有以下代码:

import React from 'react'
import type { AppProps } from 'next/app'

/* Import Styles */
import '@themes/index.scss'

/* Import Template */
import WithAuth from '@templates/with-auth'

// This default export is required in a new `pages/_app.js` file.
export const App = ({ Component, pageProps }: {Component: unknown, pageProps: unknown}): AppProps => {
  return (
    <WithAuth>
      <Component {...pageProps} />
    </WithAuth>
  )
}

export default App

I got the AppProps usage from the nextjs documentation, however I have wrapped the component with a WithAuth component which is basically a template with a MaterialUI ThemeProvider and a react context provider:我从 nextjs 文档中获得了 AppProps 的用法,但是我用WithAuth组件包装了该组件,该组件基本上是一个带有 MaterialUI ThemeProvider和一个反应上下文提供程序的模板:

 return <div className={styles['grid-page']}>
    <ThemeProvider theme={theme}>
      <GlobalContext.Provider value={globalProps}>
        <HeaderBar />
        <main>
          { children }
        </main>
      </GlobalContext.Provider>
    </ThemeProvider>
  </div>
  }

When I do this, I get the typescript error:当我这样做时,我收到 typescript 错误:

pages/_app.tsx:12:3 - error TS2322: Type 'Element' is not assignable to type 'AppPropsType<Router, {}>'.
  Property 'pageProps' is missing in type 'Element' but required in type 'AppInitialProps'.

 12   return (
      ~~~~~~~~
 13     <WithAuth>
    ~~~~~~~~~~~~~~
...
 15     </WithAuth>
    ~~~~~~~~~~~~~~~
 16   )
    ~~~

  node_modules/next/dist/next-server/lib/utils.d.ts:124:5
    124     pageProps: any;
            ~~~~~~~~~
    'pageProps' is declared here.

pages/_app.tsx:14:8 - error TS2604: JSX element type 'Component' does not have any construct or call signatures.

14       <Component {...pageProps} />

I'm struggling to understand the correct types to add here我很难理解要在此处添加的正确类型

AppProps should be de-structured. AppProps应该被解构。

import { AppProps } from 'next/app'

const MyApp = ({ Component, pageProps }: AppProps) => {
  return (
    <>
      <Header />
      <Component {...pageProps} />
    </>
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM