点击/profile后,我登录到路径/login.在/profile上再次完成登录后,我如何自动登录



我正在使用reactrouter。我没有登录,我点击了/profile链接。然后我被转发到/login(这很好(。成功登录后,我在家中登录,而不是在/配置文件

const PrivateRoute = ({ component: Component, authed, ...rest }) => (
<Route {...rest} render={props => (
authed ? 
(<Component {...props}/>) 
: 
(
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}
/>
)
)}
/>
)
render() {
const loggedIn = this.props.isLoggedIn;
return(
<Switch>
<Route exact path="/" component={ UserPanel } />
<Route exact path="/confirm" component={ EmailConfirmation } />
{/* <Route exact path="/admin" component={ AdminPanel } /> */}
<Route exact path="/login" render={(props) => ( loggedIn
? <Redirect to='/' />
: <Login/>
)} />
<PrivateRoute path='/admin' component={AdminPanel} authed = {this.props.admin}/>
<PrivateRoute path='/createevent' component={CreateEvent} authed = {loggedIn}/>
<PrivateRoute path='/profile' component={Profile} authed = {loggedIn}/>
</Switch>
)
}

目前,您似乎已经在专用路由上的Redirect上设置了一个状态:

<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}
/>

现在,您可以在登录组件上使用此状态将用户重定向回其来源。从文档中借用登录组件:

function LoginPage() {
let history = useHistory();
let location = useLocation();
let { from } = location.state || { from: { pathname: "/" } };
let login = () => {
fakeAuth.authenticate(() => {
history.replace(from);
});
};
return (
<div>
<p>You must log in to view the page at {from.pathname}</p>
<button onClick={login}>Log in</button>
</div>
);
}

从位置开始的状态被提取到变量from,或者如果它不存在(用户自愿来到路线,输入URL或单击按钮(,则默认情况下将其设置为/

稍后验证成功后,用户将重定向到from

相关内容

最新更新