如何在 slug 中从 _app.js 中排除默认组件

时间:2021-06-28 16:44:50

标签: next.js

我已经阅读了 Next.Js 的文档,我知道通过创建 _app.js 文件它将覆盖默认的 App.js 文件,因此 _app.js 文件中的那些组件将显示在每个页面上,就是我需要什么,但我还需要从 slug 中的渲染中排除其中一些组件,例如页眉或页脚,我想在除 slug 之外的所有页面上显示它们,我该怎么做?

这是我的 _app.js 代码

import React from 'react'
import Head from 'next/head';
import { ThemeProvider } from '@material-ui/core/styles';
import Header from '@/components/Header/Header'
import theme from '@/theme/theme';


function MyApp({ Component, pageProps }) {

return (
  <Head>
    <title>My App</title>
    <link rel="icon" href="/favicon.ico" />
  </Head>
  <ThemeProvider theme={theme}>
    <Header />
    <main>
      <Component {...pageProps} />
    </main>
  </ThemeProvider>
 )
}

这是我的鼻涕虫

import React from 'react'

 const MyAccounts = ({ data }) => {

const post = data && data.posts[0]
return (
      <>
        <div>
            <article>
                {post.feature_image ?
                    <figure >
                        <img src={post.feature_image} alt={post.title} />
                    </figure> : null}
                <section >
                    <h1>{post.title}</h1>
                </section>
            </article>
        </div>
        </>
)
}


 export default MyAccounts

因此在此代码中,我不希望组件 Head 显示在我的 slug 中,如何排除它?

1 个答案:

答案 0 :(得分:1)

_app.js 中,您拥有 pageProps,您可以利用它。在其中设置一些属性并基于此进行渲染。

类似于:

function MyApp({ Component, pageProps }) {

return (
  <Head>
    <title>My App</title>
    <link rel="icon" href="/favicon.ico" />
  </Head>
  <ThemeProvider theme={theme}>
    {pageProps.noLayout ? <></> : <Header />}
    <main>
      <Component {...pageProps} />
    </main>
  </ThemeProvider>
 )
}

然后在页面上添加例如:

export async function getStaticProps(context) {
  return {
    props: { noLayout: true },
  }
}