Next.js。如何在布局中调用组件的getInitialProps

时间:2018-12-06 12:26:19

标签: javascript node.js next.js

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

layout.js

<mat-vertical-stepper labelPosition="bottom" #stepper (selectionChange)="stepperEvents($event)">
    <mat-step [stepControl]="firstFormGroup">
        <form [formGroup]="firstFormGroup">
            <ng-template matStepLabel>Enter your profile name</ng-template>
            <mat-form-field>
                <input matInput placeholder="Profile Name" formControlName="firstCtrl" required>
            </mat-form-field>

            <br>
        </form>
    </mat-step>
    <mat-step [stepControl]="secondFormGroup">
        <ng-template matStepLabel>Select the working folder</ng-template>
    </mat-step>
    <mat-step>
        <ng-template matStepLabel>Done</ng-template>
        You are now done.
    </mat-step>
</mat-vertical-stepper>

header.js

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

        <Header />

        {children}
      </div>
    )

控制台:道具:{}

App.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>
        );
    }
}

我想在Header组件中使用get initial props,但不触发

1 个答案:

答案 0 :(得分:1)

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>
    )
  }
}

github的zeit有一个很好的例子