首頁  >  問答  >  主體

防止瀏覽器在我的控制台上掛起的導航限制措施

<p>為儀表板頁面建立了一個PrivateRoute,未登入時無法透過URL訪問,但刷新儀表板頁面會導致重定向到身份驗證頁面。因此,我添加了一個sessionStorage,但是現在刷新時在我的控制台上顯示"throttling navigation to prevent the browser from hanging",因為它一直在不停地重定向到頁面。</p> <p>//以下是代碼</p> <p>//App.js</p> <pre class="brush:php;toolbar:false;">從「react-router-dom」匯入 { BrowserRouter as Router, Routes, Route }; 從“./components/dashboard”導入儀表板; 從“./components/auth”導入Auth; 從“./PrivateRoute”導入PrivateRoute; 函數應用程式(){ 返回 ( <路由器> <路線> } />; <路線 路徑=“/儀表板” 元素={<PrivateRoute> <儀表板/>} >> </路線> </路由器> ); } 導出預設應用程式;</pre> <p>//PrivateRoute.js</p> <pre class="brush:php;toolbar:false;">從「react-router-dom」匯入{ Navigate }; 從“./config/firebase”導入{auth}; 函數 PrivateRoute({ 孩子 }) { const 使用者 = auth.currentUser; // 檢查使用者是否已通過身份驗證 如果(!使用者){ // 使用者未通過身份驗證,重定向到登入頁面 return <導航到=“/signin”替換/>; } // 使用者已通過身份驗證,渲染受保護的路由 返回兒童; } 匯出預設 PrivateRoute;</pre> <p>//Auth.js</p> <pre class="brush:php;toolbar:false;">從「react」匯入 { useEffect, useState }; 從“react-router-dom”導入{useNavigate}; 從“../config/firebase”導入 { auth, googleProvider }; 進口 { 建立使用者與電子郵件和密碼, 使用彈出視窗登錄, 登出, 來自“firebase/auth”; 函數驗證(){ const [電子郵件,setEmail] = useState(""); const [密碼,setPassword] = useState(""); 常量導航 = useNavigate(); console.log(auth?.currentUser?.email); useEffect(()=> { const userFromStorage = JSON.parse(sessionStorage.getItem("用戶")); 如果(用戶來自儲存){ console.log(userFromStorage); 導航(“/儀表板”); } } , [導航]); const signIn = async () =>; { 嘗試 { 等待 createUserWithEmailAndPassword(身份驗證、電子郵件、密碼); sessionStorage.setItem("用戶" , JSON.stringify(auth.currentUser)); 導航(“/儀表板”); } 捕獲(錯誤){ 控制台.錯誤(錯誤); } }; const signInWithGoogle = async () =>; { 嘗試 { 等待signInWithPopup(auth, googleProvider); sessionStorage.setItem("用戶", JSON.stringify(auth.currentUser)); 導航(“./儀表板”); }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;</pre> <p>不想要這個錯誤,作為一個初學者,如果有改進的空間,請隨時告訴我。 </p>
P粉226413256P粉226413256431 天前588

全部回覆(1)我來回復

  • P粉337385922

    P粉3373859222023-08-17 07:17:06

    您應該非同步處理身份驗證狀態。

    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;

    回覆
    0
  • 取消回覆