首页 > 解决方案 > 如何从 _app.js 中排除默认组件,使其无法在 slug 中呈现

问题描述

我已经阅读了 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 中,我该如何排除它?

标签: next.js

解决方案


_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 },
  }
}

推荐阅读