[英]ReactJs protected route redirect/refresh issue
Using react
+ react-router-dom
:使用react
+ react-router-dom
:
import React from 'react';
import { Switch, Route, Redirect } from 'react-router-dom';
And protecting a route by this:并以此保护路线:
Router路由器
const Router = () => {
return (
<Switch>
<PrivateRoute exact path='/Panel' component={Panel}></PrivateRoute>
<Route exact path='/Register' component={Register}></Route>
<Route exact path='/Login' component={Login}></Route>
</Switch>
);
};
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={props =>
Auth.getAuth() ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/Login"
}}
/>
)
}
/>
);
Auth认证
const Auth = {
isAuthenticated: false,
authenticate() {
this.isAuthenticated = true;
},
signout() {
this.isAuthenticated = false;
},
getAuth() {
return this.isAuthenticated;
}
};
So this working fine and user easily can login, logout, but the problem is when user logged I want to redirect user to /Panel
route so I tried:所以这工作正常,用户可以轻松登录,注销,但问题是当用户登录时我想将用户重定向到/Panel
路由,所以我尝试了:
window.location.href = "/Panel"
OR:或者:
this.props.history.push('/Panel')
Both redirect to /Login
again too fast, but If I click on Panel
link it going to Panel
route.两者都再次重定向到/Login
太快了,但是如果我单击Panel
链接,它将转到Panel
路由。 Second problem is when I refresh page on this address /Panel
it bring me back to /Login
again.第二个问题是,当我在此地址/Panel
上刷新页面时,它再次将我带回/Login
。 So what I want to solve are:所以我要解决的是:
Already seen this topic and tried but no success:已经看过这个话题并尝试过但没有成功:
What is the best way to redirect a page using React Router? 使用 React Router 重定向页面的最佳方式是什么?
For the first question:对于第一个问题:
You can keep the url in the state like this so that after login you can redirect to.您可以像这样将 url 保留在 state 中,以便登录后您可以重定向到。
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
And in Login component, after successfull login you can redirect to:在登录组件中,成功登录后,您可以重定向到:
const { state } = this.props.location;
window.location = state ? state.from.pathname : "/";
For the second question:对于第二个问题:
one alternative solution would be keeping the login state in localStorage so that after refreshes the app can read from there.一种替代解决方案是将登录 state 保留在 localStorage 中,以便在刷新后应用程序可以从那里读取。 This is generally done sending a jsonwebtoken from login api to the client, and saving the token to the localStorage.这通常是从登录 api 发送一个 jsonwebtoken 到客户端,并将令牌保存到 localStorage。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.