如何在静态next.js网站上返回window.location.host ?



我想返回{window.location。Host}在静态next.js网站

我设法记录了这个值,但我不知道如何返回它。

import React from "react";
import { useEffect } from "react";
export default function Test() {
useEffect(() => {
console.log(window.location.host);
}, []);
return <h1>{window.location.host}</h1>;
}

我是一个JS初学者,我所做的就是在初始页面加载时使用useEffect返回它一次,但在重新加载后它给出了错误

ReferenceError: window is not defined

窗口在服务器端渲染时不可用,你可以使用状态钩子并在你的效果钩子客户端更新它。

import {useEffect, useState} from "react";
export default function TestPage() {
const [host, setHost] = useState("");
useEffect(() => {
if (typeof window !== "undefined") setHost(window.location.host);
}, []);
return <h1>{host}</h1>;
}

最新更新