【发布时间】:2021-09-29 21:59:04
【问题描述】:
我正在使用 getServerSideProps 来获取事件的详细信息。我的理解是这些数据将在服务器上获取,然后会发生某种预渲染,然后将上下文对象传递给 _document.js。我知道 _document.js 会在每个请求上呈现,但如果该服务器数据存在,我想在我的 html 中添加一个类名(以防止在执行此客户端时闪烁)。
这是我的 getServerSideProps 函数:
export async function getServerSideProps(context) {
const shortId = context.params.short_id
const event = await GETrequest({ endpoint: API_PUBLIC_EVENT({ shortId }) })
return {
props: {
event,
shortId
} // will be passed to the page component as props
}
}
当我在 _document.js 中时,我可以看到我的 getServerSideProps 的结果可用,正如我在 getInitialProps 中记录上下文时看到的那样:
class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx)
console.log(initialProps)
// can see html that has been processed using my data
}
...
我可以想到一些在 initialProps.html 中获取我的 className 的 hacky 解决方案,但我想知道是否有更简单的方法。
有没有一种方法可以构建它,以便我的数据更容易在 _document.js 中可用,从 getServerSideProps() 传递?
【问题讨论】:
-
Next.js 自定义
_documentdoes not support data fetching methods 像getStaticProps或getServerSideProps。您应该将该逻辑移至您的自定义_app。
标签: next.js