【发布时间】:2020-08-14 07:47:55
【问题描述】:
在我的 nextjs 项目中,我有需要 api 调用的 Layout 组件。我不想在每个页面(./pages/*)中调用 api 调用,而是将逻辑放在一些全局空间中。我研究了一下,看起来覆盖 _app.js 是 nextjs 文档中指出的方法(https://nextjs.org/docs/advanced-features/custom-app)。
我已经列出了如下代码。但这似乎不起作用。
./pages/_app.js
function MyApp({ Component, appProps, results }) {
return (
<Layout {...results}>
<Component {...appProps} />
</Layout>
)
}
MyApp.getInitialProps = async (appContext) => {
const appProps = await App.getInitialProps(appContext)
const results = await getResults() //api call
return { appProps, results }
}
./components/Layout.js
const Layout = ({ children, results }) => {
return (
<React.Fragment>
<Header/>
<div className='row col-md-8 offset-md-2'>
{JSON.stringify(results)} //results is nothing here
<div className='col-md-9'>
{children}
</div>
</div>
</React.Fragment>
)
}
./pages/index.js
...
return (
<>
{head()}
<Layout>
<div className='row col-md-12'>
{showContents()}
</div>
</Layout>
</>
)
我确定我遗漏了一些明显的东西。任何帮助,将不胜感激。
【问题讨论】:
-
嗨,这是你的全部代码吗?你有什么类似“render()”函数在你的异步完成后运行吗?
标签: javascript reactjs next.js