使用 Next.js 静态生成:将页面道具传递给 Layout 组件

时间:2021-04-21 08:32:09

标签: reactjs next.js

我正在尝试将 getStaticProps 用于我的 Layout 组件,如 here 所述,但确实很难针对我的具体情况解决此问题:

_app.tsx

const NoCheck: React.FC = ({ children }) => <>{children}</>

function App({ Component, pageProps }: AppProps) {
  const neoPage = Component as NeoPage
  const LayoutComponent = neoPage.Layout || Layout

  const { withAuthCheck = true } = neoPage

  const CheckAuthComponent = withAuthCheck ? CheckAuth : NoCheck

  return (
    <CommonProviders pageProps={pageProps} overmindConfig={config}>
      <CheckAuthComponent>
        <LayoutComponent>
          <Component {...pageProps} />
        </LayoutComponent>
      </CheckAuthComponent>
    </CommonProviders>
  )
}

export default App

LayoutUnauthorized.tsx

export const LayoutUnauthorized: React.FC<Props> = ({
  children,
  systemNormal,
}) => {
  return (
    <Flex>
      <SystemStatus systemNormal={systemNormal} />
      {children}
    </Flex>
  )
}

Login.tsx(在 /page 中)

export const Login: NeoPage = () => {
  return (
    ...
  )
}

Login.Layout = LayoutUnauthorized
Login.withAuthCheck = false

export async function getStaticProps() {
  const res = await fetch("https://company.com")
  const systemNormal = await res.ok

  return {
    props: {
      systemNormal,
    },
    revalidate: 1,
  }
}

所以 Layout 有一个我希望 getStaticProps 传递的属性。如何实现?

0 个答案:

没有答案