简体   繁体   中英

Next.js , pass getServerSideProps and children props in the page component

In my Next project I have in my _app.js

function MyApp({ Component, pageProps }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  ) 
}

Layout contains some common parts of the app like the header, menu and footer. Inside Layout I have

export async function getServerSideProps(){   
    const req = await fetch(`https://jsonplaceholder.typicode.com/posts?_limit=3`) 
    const posts = await req.json();
    return {
        props:{posts}
    } 
}  

    export default function Layout({ ... props }){  

    return(
        <ThemeProvider theme={theme}>   
           <Head> </Head>
           <Navbar />  
           <div> {props.posts} </div>
           {props.children}  
           <Footer/>   
        </ThemeProvider> 
    )
}

Inside Layout, I can see only children as props. I dont see posts. I tried different approaches to insert posts in the Layout component props, nothing worked.

export default function Layout({ children, posts }){ 
export default function Layout({...{ children, posts }}){ 

nothing worked. how can I resolve this? Please help. Thanks

You can only use getServerSideProps in page components that you have in the pages folder. NextJS will see if there is a getServerSideProps function and if yes, it will invoke it and populate the data. But this only happens if NextJS is in control of the page component. So, even if you store it in the pages directory, but you import the component in some other file, you are basically taking the control away from NextJS and instantiating the component yourself.

Reference

You can use the Layout component as a wrapper only in your pages, then you can pass the props to it.

See how we achieved it here . It might require some changes to your component structure, If you edit your question with your component structure I can help you with it.

Alternatively, you can modify your _app.js like this

Only use this method if you have blocking data requirements for every single page in your application. This disables the ability to perform automatic static optimization, causing every page in your app to be server-side rendered.

import App from "next/app";

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />;
}


MyApp.getInitialProps = async (appContext) => {
  const req = await fetch(
    `https://jsonplaceholder.typicode.com/posts?_limit=3`
  );
  const posts = await req.json();

  // calls page's `getInitialProps` and fills `appProps.pageProps`
  const appProps = await App.getInitialProps(appContext);
  appProps.pageProps.posts = posts;
  return { ...appProps };
};

export default MyApp;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM