You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React:如何实现仅在网站初始加载时显示的加载组件?

解决方法

核心思路是把加载状态持久化到浏览器的localStorage中——路由切换不会清除localStorage,只有页面刷新或首次打开时才会重新读取初始值,以此保证AnimatedLogo只在初始加载/刷新时显示。

修改后的代码如下:

function App() {
  // 从localStorage读取加载状态,默认值为true
  const [loading, setLoading] = useState(() => {
    return localStorage.getItem('isAppLoaded') !== 'true';
  });

  useEffect(() => {
    // 仅当首次加载(loading为true)时执行超时逻辑
    if (loading) {
      const timer = setTimeout(() => {
        setLoading(false);
        localStorage.setItem('isAppLoaded', 'true');
        console.log("setLoading -> false");
      }, 2300);

      // 清理定时器,避免内存泄漏
      return () => clearTimeout(timer);
    }
  }, [loading]);

  return (
    <div className='App'>
      {loading ? (
        <AnimatedLogo/>
      ) : (
        <Router>
          <Navbar/>
          <Socials/>
          <Routes>
            <Route path="/" element={<Description/>}/> 
            <Route path="/about" element={<About/>} />
          </Routes>
        </Router>      
      )}    
    </div>
  );
}

关键修改点说明:

  • 状态初始化:通过useState的函数式初始化,从localStorage读取isAppLoaded的值,判断是否需要显示加载动画。如果之前已经加载过(localStorage里存了true),则直接跳过加载动画。
  • useEffect逻辑优化:仅当loading为true时才启动定时器,避免不必要的执行;超时后不仅更新状态,还把加载完成的状态存入localStorage。
  • 定时器清理:添加清理函数,在组件卸载时清除定时器,防止内存泄漏。

如果希望用户清除浏览器缓存后能再次看到加载动画,这个方案也能满足需求——清除缓存会同时清空localStorage,状态会回到初始的true。

内容的提问来源于stack exchange,提问作者Aidan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 14:34:56