问题
I created new app with Next.js 9.3.1
.
In old app with SSR. I can you getInitialProps
function in HOC components (not in page), so I can fetch data from server in HOC component and from page. Like this https://gist.github.com/whoisryosuke/d034d3eaa0556e86349fb2634788a7a1
Example :
export default function withLayout(ComposedComponent) {
return class WithLayout extends Component {
static async getInitialProps(ctx) {
console.log('ctxlayout fire');
const { reduxStore, req } = ctx || {}
const isServer = !!req
reduxStore.dispatch(actions.serverRenderClock(isServer))
if (isServer) await reduxStore.dispatch(navigationActions.getListMenuAction('menu'));
// Check if Page has a `getInitialProps`; if so, call it.
const pageProps = ComposedComponent.getInitialProps && await ComposedComponent.getInitialProps(ctx);
// Return props.
return { ...pageProps }
}
render() {
return (
<div className="app__container">
<Header />
<Navbar />
<ComposedComponent {...this.props} />
</div>
)
}
}
}
But in new version of Next.js, with SSG, I can not or I did not find the way to use getStaticProps
or getServerSideProps
in HOC components. If I use getInitialProps
in HOC (layout), I will can not use getStaticProps
or getServerSideProps
in child.
So, how can I use getStaticProps
or getServerSideProps
to fetch data and pre-render in both HOC component and page?
Thanks.
来源:https://stackoverflow.com/questions/60811497/next-js-fetch-data-in-hoc-from-server-in-ssg