我正在使用功能组件,该组件使用我的应用程序功能的使用中发生的服务器端身份验证为特定的路由(例如/ dashboard)提供身份验证。
身份验证工作正常,并且当我单击仪表板按钮时,登录后我也被定向到仪表板,否则重定向到主页。
重新加载/ dashboard page时出现问题。那时我观察到的是所有内容都被重新渲染,并且在通过使用效果之前,它首先从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()
}, [])
答案 0 :(得分:0)
请在下面尝试以下代码:
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>
);
}