【问题标题】:Render page with backend data to be used in getInitialProps in next.js在 next.js 的 getInitialProps 中使用后端数据渲染页面
【发布时间】:2020-02-04 06:05:29
【问题描述】:
我是 next.js 的新手。我在 next.js 项目中需要实现的是连接到数据库,获取一些数据,使用 express 处理它并在我的应用程序的客户端使用它。我将在快速路由处理程序中连接到数据库。问题:是否可以将下载的数据传递到客户端(即getInitialProps 生命周期方法)而不从getInitialProps 中获取它(使用for.ex.fetch api),即。有没有办法让它已经准备好通过一些道具在客户端消费(没有经典的获取方法)?
【问题讨论】:
标签:
javascript
reactjs
next.js
server-side-rendering
【解决方案1】:
你可以用类似这样的方式来获取你的数据,在 express 中:
server.get('/your/route', async (req, res) => {
// fetch your data
let data = await fetch(....)
return app.render(req, res, '/yourpage',data)
})
然后在getInitialProps 中您可以访问您的数据:
static async getInitialProps (context) {
let data = context.query;
return {data}
}