在 getInitialProps 中找不到 isServer

gha*_*san 1 reactjs next.js

我正在getInitialProps使用next.js

这是我的代码:

  static getInitialProps( ctx ) {

    console.log(ctx.isServer);
    return{}

}
Run Code Online (Sandbox Code Playgroud)

为什么我找不到isServer

iur*_*rii 5

根据文档

getInitialProps接收具有以下属性的上下文对象:

  • pathname- URL 的路径部分
  • query- URL 的查询字符串部分解析为对象
  • asPath- 实际路径(包括查询)的字符串显示在浏览器中
  • req- HTTP 请求对象(仅限服务器)
  • res- HTTP 响应对象(仅限服务器)
  • jsonPageRes- 获取响应对象(仅限客户端)
  • err- 如果渲染过程中遇到任何错误,则错误对象

因此,检查是否是服务器的最简单方法是检查 req 对象。

例子

static async getInitialProps({ req }) {
  const isServer = !!req;
  return {}
}
Run Code Online (Sandbox Code Playgroud)

这是 next.js 维护者对isServer 属性的评价

希望这有帮助!