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



我使用的是功能组件,该组件使用我的应用程序功能中发生的服务器端身份验证为特定路由(如/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>
);
}