NextJS中的What Event仅在初始加载时激发关闭



我有一个NextJS应用程序,我想让它有一个只在初始加载时运行的初始加载屏幕。当前,加载屏幕在初始加载时运行,每次单击一个链接都会将用户引导回主屏幕。我知道在React中我可以只使用window.onload(loaded(((,但在NextJS中,如果没有window对象,我如何才能获得同样的结果?我只希望loaded((函数在初始应用程序加载期间运行一次

我的代码如下,感谢您的帮助:

import Head from 'next/head';
import { useState, useEffect } from 'react';
import {
Navbar,
Hero,
Showcase,
Skills,
Services,
Footer,
ProjectCard,
Loader,
} from '../components';
const Loadera = () => {
return (
<div className="bg-blue-500 h-[100vh] w-[100vw] flex items-center justify-center text-center flex-col">
<h1 className="text-white mb-4 text-5xl ">Welcome!</h1>
<h1 className="text-white mb-4 text-2xl ">One Moment Please...</h1>
<Loader size="lg" />
</div>
);
};
export default function Home() {
const [loading, setLoading] = useState(true);
const loaded = () => {
setTimeout(() => {
setLoading(false);
}, 1500);
};
useEffect(() => {
loaded();
}, []);
return (
<div>
<Head>
<title>Seth&apos;s Place</title>
<meta
name="viewport"
content="width=device-width, initial-scale=1"
></meta>
</Head>
{loading ? (
<Loadera />
) : (
<div className="min-h-screen">
<div className="image-bg">
<Navbar />
<Hero />
</div>
<ProjectCard />
<Skills />
<Services />
<Footer />
</div>
)}
</div>
);
}

您可以创建一个标志,使加载屏幕仅在其值为unset/false时运行。在初始加载后将其值设置为true。这样,它将只加载一次。

import Head from 'next/head';
import { useState, useEffect } from 'react';
import {
Navbar,
Hero,
Showcase,
Skills,
Services,
Footer,
ProjectCard,
Loader,
} from '../components';
const Loadera = () => {
return (
<div className="bg-blue-500 h-[100vh] w-[100vw] flex items-center justify-center text-center flex-col">
<h1 className="text-white mb-4 text-5xl ">Welcome!</h1>
<h1 className="text-white mb-4 text-2xl ">One Moment Please...</h1>
<Loader size="lg" />
</div>
);
};
export default function Home() {
const [loading, setLoading] = useState({
load: true,
loadedOnce: false,
});
const loaded = () => {
setTimeout(() => {
setLoading({
load: false,
loadedOnce: true,
});
}, 1500);
};
useEffect(() => {
loaded();
}, []);
return (
<div>
<Head>
<title>Seth&apos;s Place</title>
<meta
name="viewport"
content="width=device-width, initial-scale=1"
></meta>
</Head>
{loading.load && !loading.loadedOnce ? (
<Loadera />
) : (
<div className="min-h-screen">
<div className="image-bg">
<Navbar />
<Hero />
</div>
<ProjectCard />
<Skills />
<Services />
<Footer />
</div>
)}
</div>
);
}

相关内容

  • 没有找到相关文章

最新更新