如何在组件级别获取 API 并在 nextjs 中预呈现它?

How to fetch API at component level and prerender it in nextjs?

我们需要在页脚组件中填充链接列表但是这些方法 getInitialPropsgetServerSidePropsgetStaticProps 没有在 footer 组件中执行。这是代码:

const Layout = (props) => {
    return (
        <>
            <Header />
                {props.children}
            <Footer />
        </>
    );
}
export default Layout;

--- 页脚组件 ---

    const Footer = ({data}) => {
    return(
        <ul>
            {data && data.map((todo,index)=>{
               return <li key={index}>
                    {todo.title}
                </li>
            })}
        </ul>
    );
}
export async function getStaticProps() {   // not working with getInitialProps and getServerSideProps as well
  const res = await fetch('https://jsonplaceholder.typicode.com/todos')
  const data = await res.json();

  return {
    props: {data}
  }
}
export default Footer;

编辑:Footer 组件不应显示在 Login/Signup 页中。

在 _app.js 中,我已将数据作为 <Component {...pageProps} footerData={...data} /> 传递,但数据对象在页脚组件中不可用。

getInitialPropsgetServerSidePropsgetStaticProps 仅 运行 在页面顶部,而不是组件。

如果你想 运行 在 Footer 上抓取,你可以在 useEffect 挂钩上调用抓取函数,或者简单地在 getInitialPropsgetServerSideProps, 和 getStaticProps 在页面顶部(即 _index.js)并通过 props 向下传递 Footer.

您还可以在 _app.js;

中的顶级应用程序上使用 getInitialsProps
import App, {Container} from 'next/app'
import React from 'react'
import Footer from 'somewhere/Footer';

export default class MyApp extends App {
  static async getInitialProps ({ Component, router, ctx }) {
    let pageProps = {}
    let data = await fetch('/api');
    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx)
    }

    return {data, pageProps}
  }

  render () {
    const {Component, pageProps, data} = this.props
    return <Container>
      <Component {...pageProps} footerData={data} />
    </Container>
  }
}

FooterComponent 看起来像这样

 export const Footer = ({data}) => {
    return(
        <ul>
            {data && data.map((todo,index)=>{
               return <li key={index}>
                    {todo.title}
                </li>
            })}
        </ul>
    );
}

除了登录、注册需要Footer组件的页面(Home/index.tsx, User/index.tsx)

export const Home = ({footerData}) = {
   return <div>
       <Header/>
       <Footer data={footerData} />
   </div>
}