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

未登录时如何隐藏Menu组件?如何配置useEffect实现页面自动重渲染?

问题原因

React 组件只会在状态(state)更新或者属性(props)变更时触发重渲染,localStorage 本身不是响应式数据源,你当前写的 useEffect 没有实际作用,既没有依赖项控制执行时机,也没有修改任何状态,哪怕读取了 localStorage 的值也不会触发页面更新。

修复方案

你需要做三处调整:

  • 用 useState 定义响应式的登录状态,初始值直接从 localStorage 读取
  • 监听 storage 事件,处理其他标签页修改登录状态的同步场景
  • 额外监听自定义事件,处理当前页面内执行登录/登出操作后的状态同步

修改后的完整代码如下:

import { useState, useEffect } from 'react';
// 其余原有导入保持不变

function App() {
  // 定义响应式登录状态
  const [isLoggedIn, setIsLoggedIn] = useState(() => {
    return localStorage.getItem("connexion") != null;
  });

  useEffect(() => {
    // 同步跨标签页的登录状态变更
    const handleStorageChange = (e) => {
      if (e.key === 'connexion') {
        setIsLoggedIn(e.newValue != null);
      }
    };
    // 同步当前页的登录状态变更
    const handleLocalLoginChange = () => {
      setIsLoggedIn(localStorage.getItem("connexion") != null);
    };

    window.addEventListener('storage', handleStorageChange);
    window.addEventListener('loginStatusChange', handleLocalLoginChange);
    
    // 组件卸载时清除事件监听,避免内存泄漏
    return () => {
      window.removeEventListener('storage', handleStorageChange);
      window.removeEventListener('loginStatusChange', handleLocalLoginChange);
    };
  }, []);

  return (
    <Router>
      <div>
        {isLoggedIn ? <Menu /> : <div></div>}
        <Switch>
          <Route path="/contact" component={MeContacter} />
          <Route path="/Home" component={Home} />
          <Route path="/" component={Connexion} />
        </Switch>
        <Footer />
      </div>
    </Router>
  );
}

export default App;
配套修改

你需要在登录、登出逻辑中,修改完 localStorage 的 connexion 字段后,触发自定义事件完成状态同步:

// 登录成功设置localStorage后执行
window.dispatchEvent(new CustomEvent('loginStatusChange'));

// 登出删除localStorage后执行
window.dispatchEvent(new CustomEvent('loginStatusChange'));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:18:03