Reactjs 基于身份验证的react路由器重定向
我对React是新手,在我的项目中,我使用React路由器来定义路由。但是,我有一个相同的路径要根据条件重定向。我试着把Conditional操作符放在下面,但效果不好,也厌倦了if块。如何根据条件用相同的路径渲染不同的组件Reactjs 基于身份验证的react路由器重定向,reactjs,react-router,Reactjs,React Router,我对React是新手,在我的项目中,我使用React路由器来定义路由。但是,我有一个相同的路径要根据条件重定向。我试着把Conditional操作符放在下面,但效果不好,也厌倦了if块。如何根据条件用相同的路径渲染不同的组件 var路由=( {角色===未定义( ): } );您可以使用react routeroneter钩子来保护您的路由 <Route path='/' component={Home} onEnter={requireAuth}> function requi
var路由=(
{角色===未定义(
):
}
);
您可以使用react routeroneter
钩子来保护您的路由
<Route path='/' component={Home} onEnter={requireAuth}>
function requireAuth(nextState, replace) {
if (!role) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
})
}
}
功能要求授权(下一状态,替换){
如果(!角色){
替换({
路径名:'/login',
状态:{nextPathname:nextState.location.pathname}
})
}
}
希望这有帮助。对于重定向,您可以使用
const checkRole=(nextState,replace)=>{
如果(角色===未定义)替换(“/login”)
};
...
或者您可以使用HOC(高阶组件)检查角色和其他内容
const CheckRole = Comp => class extends React.Component{
componentWillMount(){
if(role===undefined) hashHistory.replace('/signup');
}
render(){
return <Comp {...this.props}/>;
}
};
<Route path='/' component={CheckRole(Home)}>
<Route path='category' component={About}/>
...
</Route>
<Route path='/login' component={Login} />
const CheckRole=Comp=>类扩展React.Component{
组件willmount(){
if(role==未定义)hashHistory.replace('/signup');
}
render(){
返回;
}
};
...
如果您希望不同组件使用相同的路径,在某些条件下
<Route path="/" component={role===undefined ? Login : Home} />
如果使用redux,则可以使用。与单体法相比,它具有一些优点
<Route path="/" component={role===undefined ? Login : Home} />