现在,我有一个错误的window is not defined
在NextJs上初始化一个变量。我想知道最后一次访问该网站时,窗口加载。
编辑
注意我使用的是Function Component
import { useState } from "react";
import LoadingScreen from "../components/LoadingScreen";
import { AppContext } from "../contexts/AppContext";
function MyApp({ Component, pageProps }) {
const [deltaTime, setDeltaTime] = useState(() => {
if (typeof window !== undefined) {
window.onload = () => {
let lastTimeLoaded =
localStorage.getItem("@services_site/loadingTime") || null;
deltaTime = new Date() - 1000 * 20 - new Date(lastTimeLoaded);
localStorage.setItem("@services_site/loadingTime",new Date());
console.log("deltaTime is", deltaTime);
return deltaTime;
};
}
return 0;
});
return (
<>
{deltaTime < 0 && <LoadingScreen />}
<AppContext.Provider value={deltaTime}>
<Component {...pageProps} />
</AppContext.Provider>
</>
);
}
所以我将代码移动到useEffect
if (typeof window !== undefined) {
window.onload = () => {
let lastTimeLoaded =
localStorage.getItem("@services_site/loadingTime") || null;
let delta = new Date() - 1000 * 20 - new Date(lastTimeLoaded);
console.log("deltaTime is", delta);
localStorage.setItem("@services_site/loadingTime", new Date());
setDeltaTime(delta);
};
}
}, [deltaTime]);```