我有一个网站,现在无论我是否登录,当我转到根目录时,它都会显示我的登录表单。我想要的是,如果我登录并进入 /
重定向到 /api/admin
这是我的路线配置:
const routes = {
path: '/',
component: App;
indexRoute: { component: Login },
childRoutes: [
{ path: 'twitter', component: TwitterIn },
]
}
我的问题是如何在这里进行登录,例如
if (UserLogged) {
//goto /api/admin
} else {
//behave just like is behaving now
}
最佳答案
如果您使用的是 React-Router,请使用 withRouter
包装默认导出的组件。您可以使用以下方式导入它:
import { withRouter } from "react-router";
当您使用默认导出时,您可以这样做:
const Comp extends React.Component {
// ...
}
export default withRouter(Comp);
withRouter
高阶组件将通过更新 match
, location
,和history
每当渲染时,都会向包装的组件提供 Prop 。
并且在构造函数中或在检查条件的任何位置,您可以使用 this.props.history
并以这种方式重定向:
if (UserLogged) {
// goto /api/admin
this.props.history.replace("/api/admin");
}
如果不可能,您可以使用 <Redirect />
API,可以通过以下方式导入:
import { Route, Redirect } from 'react-router';
只有当您位于渲染函数内部时(我猜),这才有效。
render() {
if (UserLogged) {
// goto /api/admin
return <Redirect to="/api/admin" />;
}
return (
<p>Your usual HTML</p>
);
}
关于javascript - 如果登录应用程序如何重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56153937/