我是 React 新手,在我的项目中我使用了 React-router 来定义路由。但是,我有根据条件重定向的相同路径。我尝试将条件运算符如下所示,但不起作用,也厌倦了 if block 。如何根据条件使用相同的路径渲染不同的组件。
var Routes = (
<Router history={hashHistory}>
{role === undefined ? (
<Route path='/' component={Login} />
):
<Route path='/' component={Home}>
<Route path='category' component={About}/>
<Route path='input' component={Cate} />
<Route path='charts' component={Chart}/>
<Route path='buyerHome' component={customer}/>
</Route>
}
</Router>
);
最佳答案
您可以使用react-router onEnter
hook来保护您的路由。
<Route path='/' component={Home} onEnter={requireAuth}>
function requireAuth(nextState, replace) {
if (!role) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
})
}
}
希望这有帮助。
关于reactjs - 使用react-router进行基于身份验证的重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38279555/