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

React-Redux与Firebase登出后路由未跳转问题求助

React-Redux + Firebase 登出后页面未跳转问题

问题详情

登录后处于/profile路径,点击登出按钮后UI已切换为登出状态,但页面仍停留在/profile,未自动跳转到登录页/。

相关代码

Redux 用户切片

export const userSlice = createSlice({
  name: "user",
  initialState: {
    user: null,
  },
  reducers: {
    login: ( state, action ) => {
      state.user = action.payload;
    },
    logout: (state) => {
      state.user = null;
    }
  },
});

App 组件

function App() {
  const user = useSelector(selectUser);
  const dispatch = useDispatch();
  
  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((userAuth) => {
      if (userAuth) {
        // logged in
        dispatch(login({
          uid: userAuth.uid,
          email: userAuth.email,
        }))
      } else {
        // logged out
        dispatch(logout())
      }
    });
    return unsubscribe;
  }, [dispatch]);

  return (
    <div className="app">
      <BrowserRouter>
        {!user ? (
          <Routes>
            <Route path="/" element={<LoginScreen />} />
          </Routes>
        ) : (
          <Routes>
            <Route path="/profile" element={<ProfileScreen/> } />
            <Route exact path="/" element={<HomeScreen />} />
          </Routes>
        )}
      </BrowserRouter>
    </div>
  )
}

登出按钮

<button
  onClick={()=>auth.signOut()}
  className="profileScreen_SignOut"
>
  Sign Out
</button>

原因分析

当前代码仅在Firebase的auth.onAuthStateChanged回调中更新了Redux的用户状态,触发UI切换,但没有处理登出后的页面导航逻辑。浏览器地址停留在/profile,虽然未登录时的路由配置不渲染ProfileScreen,但不会自动跳转。

解决方法

方法1:在状态监听回调中添加跳转

修改App组件,使用useNavigate钩子在登出时主动跳转到登录页,同时添加路由守卫避免未登录访问/profile:

import { BrowserRouter, Routes, Route, useNavigate, Navigate } from 'react-router-dom';

function App() {
  const user = useSelector(selectUser);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  
  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((userAuth) => {
      if (userAuth) {
        dispatch(login({
          uid: userAuth.uid,
          email: userAuth.email,
        }))
      } else {
        dispatch(logout());
        navigate('/'); // 登出后立即跳转登录页
      }
    });
    return unsubscribe;
  }, [dispatch, navigate]);

  return (
    <div className="app">
      <BrowserRouter>
        {!user ? (
          <Routes>
            <Route path="/" element={<LoginScreen />} />
            {/* 未登录时访问profile直接重定向到登录页 */}
            <Route path="/profile" element={<Navigate to="/" />} />
          </Routes>
        ) : (
          <Routes>
            <Route path="/profile" element={<ProfileScreen/> } />
            <Route exact path="/" element={<HomeScreen />} />
          </Routes>
        )}
      </BrowserRouter>
    </div>
  )
}

方法2:在登出按钮点击事件中处理跳转

直接在登出按钮的回调里,等Firebase登出操作完成后执行跳转:

import { useNavigate } from 'react-router-dom';

function ProfileScreen() {
  const navigate = useNavigate();

  return (
    // ...其他组件内容
    <button
      onClick={() => {
        auth.signOut().then(() => {
          navigate('/');
        }).catch(err => {
          console.error('登出失败:', err);
        });
      }}
      className="profileScreen_SignOut"
    >
      Sign Out
    </button>
    // ...其他组件内容
  )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 19:31:25