You need to enable JavaScript to run this app. React中如何将Login子组件的登录状态传给父组件用于Protected Route鉴权
优惠活动
大模型
产品
解决方案
定价
更多

React中如何将Login子组件的登录状态传给父组件用于Protected Route鉴权

解决方案

步骤1:重构根代码,新增状态管理登录态

原index.js直接渲染路由没有状态管理能力,我们先抽离出顶层App组件存储全局登录状态,同时初始化时从localStorage读取历史登录状态,避免页面刷新后登录态丢失:

import { useState } from 'react';
import { createBrowserHistory, Router, Switch, Route } from 'react-router-dom';
import Login from './Login';
import AdminLayout from './AdminLayout';
import ProtectedRoute from './ProtectedRoute'; // 替换为你自己的ProtectedRoute组件路径

const hist = createBrowserHistory();

// 新增顶层App组件管理全局登录态
const App = () => {
  // 初始化时从localStorage读取登录状态
  const [isAuth, setIsAuth] = useState(() => {
    return !!localStorage.getItem('user-info');
  });

  return (
    <Router history={hist}>
      <Switch>
        <Route 
          path="/" 
          exact 
          // 给Login组件传递更新登录态的回调方法
          component={(props) => <Login {...props} onLoginSuccess={() => setIsAuth(true)} />} 
        />
        <ProtectedRoute 
          path="/admin" 
          component={(props) => <AdminLayout {...props} />} 
          isAuth={isAuth} // 替换硬编码的true,使用动态状态校验
        />
        <Route path="" component={() => "404 NOT FOUND"} />
      </Switch>
    </Router>
  )
}

ReactDOM.render(<App />, document.getElementById("root"));

步骤2:修改Login组件,登录成功后同步更新全局状态

接收父组件传入的回调方法和路由跳转能力,登录校验通过后触发回调更新全局登录态,同时跳转到仪表盘页面:

// 新增接收props:onLoginSuccess是父组件传的更新登录态方法,history是路由跳转API
const Login = ({ submitForm, onLoginSuccess, history }) => {
  const [isSubmitted, setIsSubmitted] = useState(false);

  function submitForm() {
    setIsSubmitted(true);
  }
  const { handleChange, values, handleSubmit, errors } = useForm(
    submitForm,
    validate
  );

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(false);

  const fetchLogin = async (email, password) => {
    try {
      setLoading(true);
      const res = await Axios({
        data: {
          user_email: email,
          user_password: password,
        },
      });
      if (res.status === 200) {
        localStorage.setItem("user-info", JSON.stringify(res));
        // 调用父组件回调更新全局登录态
        onLoginSuccess();
        // 跳转到仪表盘页面
        history.push('/admin');
      }
      setLoading(false);
    } catch (err) {
      setError(err.message);
      setLoading(false);
    }
  };

  function loginButton() {
    fetchLogin(values.email, values.password);
  }
  return (
    <form onSubmit={handleSubmit(loginButton)}>
      {/* 你的原有表单内容 */}
    </form>
  );
};

export default Login;

补充说明

  • 请确保你的ProtectedRoute组件内部逻辑正常:当isAuth为false时,自动重定向到登录页/
  • 退出登录功能只需清除localStorage的user-info,再调用setIsAuth(false)即可重置鉴权状态
  • 如果项目后续规模扩大,建议使用Context API或者轻量状态管理库(如Zustand)管理登录态,避免props多层传递的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 00:36:08