防止浏览器在我的控制台上挂起的导航限制措施
P粉226413256
P粉226413256 2023-08-16 08:43:57
[JavaScript讨论组]

为仪表板页面创建了一个PrivateRoute,未登录时无法通过URL访问,但刷新仪表板页面会导致重定向到身份验证页面。因此,我添加了一个sessionStorage,但是现在刷新时在我的控制台上显示"throttling navigation to prevent the browser from hanging",因为它一直在不停地重定向到页面。

//以下是代码

//App.js

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Dashboard from "./components/dashboard";
import Auth from "./components/auth";
import PrivateRoute from "./PrivateRoute";

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/signin" element={<Auth />} />
        <Route
          path="/dashboard"
          element={<PrivateRoute> <Dashboard /></PrivateRoute>}
        />
      </Routes>
    </Router>
  );
}

export default App;

//PrivateRoute.js

import {  Navigate } from "react-router-dom";
import { auth } from "./config/firebase";

function PrivateRoute({ children }) {
  const user = auth.currentUser;

  // 检查用户是否已经通过身份验证
  if (!user) {
    // 用户未通过身份验证,重定向到登录页面
    return <Navigate to="/signin" replace/>;
  }

  // 用户已通过身份验证,渲染受保护的路由
  return children;
}

export default PrivateRoute;

//Auth.js

import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { auth, googleProvider } from "../config/firebase";
import {
  createUserWithEmailAndPassword,
  signInWithPopup,
  signOut,
} from "firebase/auth";

function Auth ()  {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const navigate = useNavigate();

  console.log(auth?.currentUser?.email);

  useEffect(()=> {
    const userFromStorage = JSON.parse(sessionStorage.getItem("user"));
    if(userFromStorage){
      console.log(userFromStorage);
      navigate("/dashboard");
    }
  } , [navigate]);

  const signIn = async () => {
    try {
      await createUserWithEmailAndPassword(auth, email, password);
      sessionStorage.setItem("user" , JSON.stringify(auth.currentUser));
      navigate("/dashboard");
    } catch (err) {
      console.error(err);
    }
  };

  const signInWithGoogle = async () => {
    try {
      await signInWithPopup(auth, googleProvider);
      sessionStorage.setItem("user", JSON.stringify(auth.currentUser));
      navigate("./dashboard");
    } catch (err) {
      console.error(err);
    }
  };

  const Logout = async () => {
    try {
      await signOut(auth);
      sessionStorage.removeItem("user");
    } catch (err) {
      console.error(err);
    }
  };

  return (
    <div>
      <input placeholder="email" onChange={(e) => setEmail(e.target.value)} />
      <input
        type="password"
        placeholder="password"
        onChange={(e) => setPassword(e.target.value)}
      />
      <button onClick={signIn}>sign in</button>
      <button onClick={signInWithGoogle}>sign in with Google</button>
      <button onClick={Logout}>Logout</button>
    </div>
  );
};
export default Auth;

不想要这个错误,作为一个初学者,如果有改进的空间,请随时告诉我。

P粉226413256
P粉226413256

全部回复(1)
P粉337385922

您应该异步处理身份验证状态。

import { useEffect, useState } from 'react';
import { Navigate } from 'react-router-dom';
import { auth } from './config/firebase';

function PrivateRoute({ children }) {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // 观察用户身份验证变化
    const unsubscribe = auth.onAuthStateChanged((user) => {
      if (user) {
        setIsAuthenticated(true);
      } else {
        setIsAuthenticated(false);
      }
      setLoading(false);
    });

    // 当组件卸载时取消订阅
    return () => unsubscribe();
  }, []);

  if (loading) return <div>加载中...</div>; // 可选的加载指示器

  if (!isAuthenticated) {
    return <Navigate to="/signin" replace />;
  }

  return children;
}

export default PrivateRoute;
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号