我有一个网站,现在无论是否登录,当我进入根目录时都会显示我的登录表单。我想要的是,如果我已登录并进入/
重定向到/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
}
答案 0 :(得分:1)
如果您使用的是React-Router,请使用withRouter
包装默认的导出组件。您可以使用以下命令导入它:
import { withRouter } from "react-router";
使用默认导出时,您可以通过以下方式进行操作:
const Comp extends React.Component {
// ...
}
export default withRouter(Comp);
withRouter
高阶组件将在渲染后将更新的match
,location
和history
道具传递给包装的组件。
在构造函数中或您要检查条件的任何地方,都可以使用this.props.history
并以这种方式重定向:
if (UserLogged) {
// goto /api/admin
this.props.history.replace("/api/admin");
}
如果无法实现,则可以使用<Redirect />
API,该API可以通过以下方式导入:
import { Route, Redirect } from 'react-router';
这仅在您位于渲染功能内部时才有效(我想)。
render() {
if (UserLogged) {
// goto /api/admin
return <Redirect to="/api/admin" />;
}
return (
<p>Your usual HTML</p>
);
}
答案 1 :(得分:0)
在我的上一个项目中,我定义了React组件中的所有路由。在该组件中,“用户”定义为状态属性,设置为“空”(注销)或有效的用户对象(登录)。然后,如果用户已注销,则组件的呈现逻辑将返回一组路由(重定向到登录页面),如果用户已登录,则返回另一组路由(完整的应用程序路由)。