总是在刷新时重新路由到主页

Always getting Re - Routed to home page on refresh

我正在使用功能组件为特定路由提供身份验证,例如 /dashboard 使用服务器端身份验证发生在我的应用程序功能的使用效果中。

身份验证工作正常,而且当我单击仪表板按钮时,我在登录时被定向到仪表板,否则重定向到主页。

当我重新加载 /dashboard 页面时出现问题。那时我观察到的是一切都被重新渲染,在通过使用效果之前,它首先从 AuthenticatedRoute 传递,它不提供身份验证,因为服务器端身份验证正在使用效果中发生,我被直接重定向到主页,即使我是已登录。

App.js

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

路线代码:

App.js

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

App.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>
    );
}