【发布时间】:2021-01-22 04:38:56
【问题描述】:
每次我在令牌过期后尝试导航到某个页面时,都不会被重定向到我的登录页面。理想情况下,我希望在我的令牌过期后被重定向到我的登录页面。我的状态变量在令牌过期时会更新,但在呈现重定向组件时会被忽略。我认为我的私人路线可能写错了。
App.js
import { BrowserRouter as Router, Route, Switch, Redirect } from "react-router-dom";
import LandingPage from './pages/LandingPage';
import ViewAllRecipe from './pages/ViewAllRecipe';
import AddRecipe from './pages/AddRecipe';
import EditRecipe from './pages/EditRecipe';
import SingleRecipe from './pages/SingleRecipe';
import axios from 'axios';
var status;
async function validToken(){
var token = localStorage.getItem('token');
try{
const res = await axios.post('/api/auth/verify',
{token: token},
{headers: {'Content-Type': 'application/json'}},
);
if(res.data.status===200){
status = 200;
}
else{
localStorage.removeItem('token');
status= 401;
}
}
catch(err){
localStorage.removeItem('token');
status=500;
}
}
function PrivateRoute({ children, ...rest }) {
validToken();
return (
<Route
{...rest}
render={() =>
status!==200 ? (
<Redirect
to="/landing"
/>
):(
children
)
}
/>
);
}
function App() {
return (
<Router>
<Switch>
<Route exact path="/landing" component={LandingPage}></Route>
<PrivateRoute exact path="/addRecipe" component={AddRecipe}></PrivateRoute>
<PrivateRoute exact path="/viewRecipes" component={ViewAllRecipe}></PrivateRoute>
<PrivateRoute exact path="/recipe/edit/:editRecipe" component={(props) => <EditRecipe {...props}/>}></PrivateRoute>
<PrivateRoute exact path="/recipe/view/:id" component={(props) => <SingleRecipe {...props}/>}></PrivateRoute>
</Switch>
</Router>
);
}
export default App; ```
【问题讨论】:
-
validToken是异步的,这意味着状态在PrivateRoute返回组件之后发生变化。 -
@ChrisG 这是有道理的。我应该如何设置它以避免进行异步调用?
-
授权请求需要一点时间才能完成,所以如何处理这取决于你想在此期间向用户显示什么。我不确定最好的方法是什么,tbh。
标签: javascript reactjs react-redux local-storage react-router-dom