首页 > 解决方案 > 如何在 gatsby 中获取主机名?

问题描述

我正在尝试在我在 gatsby 项目中编写的实用程序文件中获取主机名。但它会抛出这样的错误

WebpackError: ReferenceError: window is not defined

实用程序文件:

export const getHostName = () => {
  if (typeof window !== 'undefined' || typeof document !== 'document' ) {
    return window?.location?.hostname || document?.location?.hostname;
  }
}

有什么办法可以解决这个错误。或者我们可以在这里使用它来获取主机名的任何其他替代方法

标签: javascriptreactjsreact-hooksgatsby

解决方案


像这样使用它:

export const getHostName = () => {
  if (typeof window !== 'undefined') {
    return window?.location?.hostname || document?.location?.hostname;
  }
}

条件的第二部分几乎总是被验证,它破坏了你的代码。

请记住,该getHostName函数应该在 React 生命周期方法中调用(useEffect例如),否则它不会显示任何内容。


推荐阅读