簡體   English   中英

總是在刷新時重新路由到主頁

[英]Always getting Re - Routed to home page on refresh

我正在使用功能組件,它使用我的應用程序功能的使用效果中發生的服務器端身份驗證為特定路由(例如 /dashboard)提供身份驗證。

身份驗證工作正常,並且當我單擊儀表板按鈕時,我會在登錄時被定向到儀表板,否則會重定向到主頁。

當我重新加載 /dashboard 頁面時出現問題。 那時我觀察到的是一切都被重新渲染,在通過使用效果之前,它首先從不提供身份驗證的 AuthenticatedRoute 傳遞,因為服務器端身份驗證正在使用效果中發生,我被直接重定向到主頁,即使我在登錄。

應用程序.js

const AuthenticatedRoute = ({ children, isAuthenticated , ...rest }) => {
  return (
    <Route
      {...rest}
      render={() =>
        isAuthenticated ? (
            <div>{children}</div>
        ) : (
          <Redirect to="/home" />)}
    ></Route>
  );
};

路線代碼:

應用程序.js

<AuthenticatedRoute isAuthenticated = {isAuthenticated} path="/dashboard">
    <AgentDashboard />
</AuthenticatedRoute> 

應用程序.js

function App() {

    const [authTokenValid, setauthTokenValid] = useState(false)
    
    useEffect(() => {
    
        const token = localStorage.getItem('Authorization')
        const authMainPageCheck = async () => {
            await axios.post(tokenAuthCheckURL , {
                'token':token,
            }).then(result => result.data).then(
                result => {
                    if(result.status === 200){
                        console.log("Authentication Given ")
                        setauthTokenValid(true)
                    }
                    else{
                        console.log("Authentication Not Given ")
                        setauthTokenValid(false)
                    }
                })
        }
        authMainPageCheck()
}, [])

請嘗試以下代碼:


import React, { useEffect, useState } from "react";
import { Route, Redirect, BrowserRouter } from "react-router-dom";
// import axios from "axios";

// @ts-ignore
const AuthenticatedRoute = ({ children, isAuthenticated, ...rest }) => {
  return (
    <Route
      {...rest}
      render={() =>
        isAuthenticated ? (
          <div>
            {children}
          </div>
        ) : (<Redirect to="/error" />)
      }
    ></Route>
  );
};


export const App = () => {

  // Set initial value to null
  const [authTokenValid, setauthTokenValid] = useState(null)

  useEffect(() => {

    // Wait for request to complete
    // Example...
    setTimeout(() => {
      // @ts-ignore
      setauthTokenValid(true);
    }, 3000);

    // const token = localStorage.getItem('Authorization');
    // const authMainPageCheck = async () => {
    //   await axios.post(tokenAuthCheckURL, {
    //     token,
    //   }).then(result => result.data).then(
    //     result => {
    //       if (result.status === 200) {
    //         console.log("Authentication Given ")
    //         setauthTokenValid(true)
    //       } else {
    //         console.log("Authentication Not Given ")
    //         setauthTokenValid(false)
    //       }
    //     }
    //   )
    // }
  }, []);

  if (authTokenValid === null)
    // Wait Until a Non Null Response Comes....
    return (<h1>Loading...</h1>); // Create a new loading component...

  else
    return (
      <BrowserRouter>

        <AuthenticatedRoute isAuthenticated={authTokenValid} exact path="/">
          <h1>This is Authenticated Home!!!</h1>
        </AuthenticatedRoute>

        <AuthenticatedRoute isAuthenticated={authTokenValid} exact path="/dashboard">
          <h1>This is Authenticated Dashboard!!!</h1>
        </AuthenticatedRoute>

      </BrowserRouter>
    );
}


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM