Next.js。 Layout中如何调用组件的getInitialProps

Next.js. How to call component's getInitialProps in Layout

我将页眉组件添加到布局,但我不想为我想要使用 getInitialProps 的每个页面将道具从布局发送到页眉

layout.js

import Header from './header'
export default ({title}) => (
      <div>
        <Head>
          <title>{ title }</title>
          <meta charSet='utf-8' />
        </Head>

        <Header />

        {children}
      </div>
    )

header.js

export default class Header extends Component {
    static async getInitialProps () {
      const headerResponse = await fetch(someapi)
      return headerResponse;
    }
    render() {
        console.log({props: this.props})
        return (
            <div></div>
        );
    }
}

控制台:道具:{}

App.js

  import Layout from './layout'
  import Page from './page'
  import axios from 'axios'

const app =  (props) => (
  <Layout >
    <Page {...props}/>
  </Layout>
)

app.getInitialProps = async function(){
  try {
    const response = await axios.get(someUrl)
    return response.data;

  } catch(e) {
    throw new Error(e);
  }
}

export default app

我想在 Header 组件中使用 get initial props 但它没有触发

编辑:2021 年这样做的方式:

// with typescript remove type if you need a pure javascript solution
// _app.tsx or _app.jsx
import type { AppProps } from 'next/app';

import Layout from '../components/Layout';

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

  return (
    <Layout {...pageProps}>
      <Component {...pageProps} />
    </Layout>
  );
}

// In order to pass props from your component you may need either `getStaticProps` or `getServerSideProps`.
// You should definitely not do that inside your `_app.tsx` to avoid rendering your whole app in SSR;
// Example for SSR
export async function getServerSideProps() {
  // Fetch data from external API
  const res = await fetch(`https://.../data`)
  const data = await res.json()

  // Pass data to the page via props
  return { props: { data } }
}

Next.js使用App组件初始化页面。您可以覆盖它并控制页面初始化。

你可以做的是,将你的逻辑放在 _app 覆盖中并将其传递给你的子组件,例如 Layout 组件。

创建一个page/_app.js

import React from 'react'
import App, { Container } from 'next/app'

import Layout from '../components/Layout'

export default class MyApp extends App {
  static async getInitialProps({ Component, router, ctx }) {
    let pageProps = {}
    

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx)
    }

    /* your own logic */

    return { pageProps }
  }

  render () {
    const { Component, pageProps } = this.props

    return (
      <Container>
        <Layout {...pageProps}>
          <Component {...pageProps} />
        </Layout>
      </Container>
    )
  }
}

zeit 在 github

有一个很好的例子