javascript - 如何在 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;
}
}
有什么办法可以解决这个错误。或者我们可以在这里使用它来获取主机名的任何其他替代方法
解决方案
像这样使用它:
export const getHostName = () => {
if (typeof window !== 'undefined') {
return window?.location?.hostname || document?.location?.hostname;
}
}
条件的第二部分几乎总是被验证,它破坏了你的代码。
请记住,该getHostName
函数应该在 React 生命周期方法中调用(useEffect
例如),否则它不会显示任何内容。
推荐阅读
- python - 在多个空格但不是单个空格上拆分字符串
- java - 如果条件为真,我如何每秒自动运行一个按钮,直到 de 条件成立?
- github - 在 /blog 目录中安装 Gatsby
- python - 我的 base 10 或一般代码有什么问题
- java - 如何在 TextView 中压倒自动调整大小?
- javascript - Redux 商店在刷新浏览器时不刷新(清除)
- amazon-web-services - S3 存储桶策略不允许 Athena 执行查询
- php - 根据在 WooCommerce 中选择的运输方式添加费用
- python - 从整数列表中返回元素的索引值
- php - PHP shell_exec 在第二次 Ajax 调用时停止工作