gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 00:35:29 24 4
gpt4 key购买 nike

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

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

控制台: Prop :{}

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 有一个很好的例子

关于javascript - Next.js。 Layout中如何调用组件的getInitialProps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53651439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com