以下是一个使用 Next.js 实现服务端渲染的示范代码:
- 创建一个基于 Next.js 的项目
npx create-next-app my-app
cd my-app
npm run dev
- 创建一个页面(例如
pages/index.js
)
function HomePage({ currentDateTime }) {
return (
<>
<h1>Hello world!</h1>
<p>The current date and time is: {currentDateTime}</p>
</>
)
}
HomePage.getInitialProps = async () => {
const response = await fetch('http://worldclockapi.com/api/json/utc/now')
const data = await response.json()
return { currentDateTime: data.currentDateTime }
}
export default HomePage
-
在
getInitialProps
函数中进行数据获取,并将获取到的数据作为 props 传递给组件。在这个例子中,我们调用了世界时钟 API,获取了当前时间。 -
启动应用,访问 http://localhost:3000 可以看到应用渲染出的 HTML。这个 HTML 是在服务端生成的,包含了当前时间。
Next.js 的服务端渲染功能从头到脚提供了这个示例代码。你可以随时在你的开发项目中实现服务端渲染。