reactjs - 单击 /profile 后,我登陆路径 /login。在 /profile 上再次完成登录后如何自动登陆?
问题描述
我正在使用 reactrouter。我没有登录我点击 /profile 链接。然后我被转发到 /login (工作正常)。成功登录后,我登陆家而不是 /profile
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 }
}}
/>
现在,您可以在 Login 组件上利用此状态将用户重定向回他的来源。从docs借用 Login 组件:
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>
);
}
来自 location 的状态被提取到一个变量中,from
或者如果它不存在(用户根据自己的意愿来到路线,输入 URL 或单击按钮)将其/
默认设置为。
稍后在成功验证后,用户被重定向到from
.
推荐阅读
- .net - 我可以将 Entity Framework Core 6 与 Windows 窗体一起使用(使用 .NET 5)吗?
- javascript - 在数组的javascript find() 方法中,如何仅使用回调函数的数组参数来获取任何元素?请参阅下面的代码
- java - java - 如何在Java的嵌套循环中只迭代一次for循环?
- mysql - MySQL如何从列值中的mutiplitcaton返回值
- flutter - hydrad_bloc:未处理的异常:对空值使用空检查运算符
- javascript - 如何访问 Shopware 6 店面的 Javascript 中的翻译?
- angular - Angular - 错误:类型“MatPaginator”不满足约束“MatTableDataSourcePaginator”
- flutter - 登录成功后如何禁止返回登录页面?
- c++ - 在二叉树中求平均值的问题
- rust - rust 函数接受闭包作为参数或返回闭包的惯用方式是什么?