[英]Redirect logged user from login/register page with React Hooks
I would like to handle behavior when logged user will try to access login/register/any related view, to redirect such request to homepage, using react-hooks.我想处理登录用户尝试访问登录/注册/任何相关视图时的行为,以使用 react-hooks 将此类请求重定向到主页。 I've tried something like this, on top of my login form component:在我的登录表单组件之上,我尝试过这样的事情:
useEffect(() => {
if (isAuthenticated) history.push("/dashboard");
}, [isAuthenticated, history]);
But every time logged user clicks on login, he/she sees login form for glimpse of and eye and I would like to prevent it.但是每次登录的用户点击登录时,他/她都会看到登录表单以便一瞥和眼睛,我想阻止它。 As a workaround, I've come with NotLoggedRoute
, which mimics PrivateRoute
behavior, but I'm not sure if this is the best way to handle it such way:作为一种解决方法,我提供了NotLoggedRoute
,它模仿PrivateRoute
行为,但我不确定这是否是处理它的最佳方式:
import React from "react";
import { Route, useHistory } from "react-router-dom";
import { useSelector } from "react-redux";
export const NotLoggedRoute = ({ component: Component, ...rest }) => {
const isLogged = useSelector(state => state.user.isLogged);
const history = useHistory();
return (
<Route {...rest} render={props =>
isLogged ? history.push("/home") :<Component {...props} />
}
/>
);
};
I'm using react-router-dom v5.1.2, react 16.9 and react-redux 7.2.0我正在使用 react-router-dom v5.1.2、react 16.9 和 react-redux 7.2.0
Basically your direction is correct but you can leverage here Redirect
component from react-router-dom
and children
prop - define PublicRoute
which handle the logic and wrap all your public components with it:基本上你的方向是正确的,但你可以在这里利用Redirect
component from react-router-dom
和children
prop - 定义处理逻辑并用它包装所有公共组件的PublicRoute
:
import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import { useSelector } from 'react-redux';
const PublicRoute = ({ children, ...rest }) => {
const isLogged = useSelector(state => state.user.isLogged);
return (
<Route
{...rest}
render={() => {
if (isLogged) {
return <Redirect to="/home" />;
}
return children;
}}
/>
);
};
export default PublicRoute;
<PublicRoute path="/login">
<Login />
</PublicRoute>
<PublicRoute path="/register">
<Register />
</PublicRoute>
etc... ETC...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.