最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Next.js. How to call component's getInitialProps in Layout - Stack Overflow

programmeradmin3浏览0评论

I add header ponent to layout but i don't want to send props from layout to header for every page I want use 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>
        );
    }
}

console: props: {}

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

I want to use get initial props in Header ponent but it not firing

I add header ponent to layout but i don't want to send props from layout to header for every page I want use 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>
        );
    }
}

console: props: {}

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

I want to use get initial props in Header ponent but it not firing

Share Improve this question asked Dec 6, 2018 at 12:26 Aliaga AliyevAliaga Aliyev 4251 gold badge7 silver badges23 bronze badges 1
  • getInitialProps is only available at the top level of your application (page), however you can pass props inside your ponents – Fabien Greard Commented Dec 6, 2018 at 18:31
Add a ment  | 

1 Answer 1

Reset to default 11

EDIT: 2021 way of doing this :

// 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 '../ponents/Layout';

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

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

// In order to pass props from your ponent 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 uses the App ponent to initialize pages. You can override it and control the page initialization.

What you could do is, put your logic inside the _app override and pass it to your children ponents, example with a Layout ponent.

Create a page/_app.js

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

import Layout from '../ponents/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>
    )
  }
}

There is a good example from zeit at github

发布评论

评论列表(0)

  1. 暂无评论