我找到了一堆React Router'auth'示例,所有这些示例都使用replaceState转到登录路由,然后在登录后转到固定位置。我正在寻找的是一个示例,其中登录和注册是模态的(不直接绑定到他们自己的路由),这些是基于状态的,并且可以随时随地通过app触发。
我想做的是,如果用户通过GUI调用操作或直接转到“需要auth”并且未登录的URL /路由,请显示模态,然后登录和/或注册后/ login然后发送到他们试图去的路线。否则将它们发送到它们来自的路线或主页(如果不是先前路线)(即它们直接在浏览器中输入URL)。
我能够找到的东西假设登录是它自己的路线,然后重定向到某个固定位置(而不是用户首先尝试去的地方)。请记住,用户可以在注册和登录模式之间切换任意次数,因此我需要在他们想要去的地方坚持到他们取消或成功为止。如果取消,很容易,但取决于成功的地点和方式,我可以坚持,然后转换到所要求的路线?
TIA
答案 0 :(得分:1)
我可以想到两种可能的方式:
<Route/>
具体pageCompoenent
扩展AuthComponent
,默认情况下会处理登录或注册模式的显示。<Route/>
具体pageCompoenent
都是父<Route/>
组件AuthHandler
的子级,通过{this.props.children}
呈现所有子路由。我个人更喜欢第二种解决方案。示例代码:
// Soln2
// Route Declaration
<Route name='auth' path='/' component={AuthHandler}>
<Route name='settings' path='/settings' component={SettingsPage} />
<Route name='about' path='/about' component={AboutPage} />
<Route name='someother' path='/someother' component={SomeOtherPage} />
</Route>
// AuthHandler
class AuthHandler extends React.Component{
componentWillMount(){
if(!Authenticated) showLoginRegisterModal();
}
componentWillReceiveProps(){
if(!Authenticated) showLoginRegisterModal();
}
showLoginRegisterModal(){
// Handle how you wish to show your modal, by style/class/this.state.ifShow
}
render(){
return(
<div>
<ModalComponent ifShow={this.state.ifShow}/>
<div {...this.props}>
{this.props.children} // Your child pages will get rendered here
</div>
</div>
)
}
}
class ModalComponent extends React.Component{
// Some member functions
render(){
return(
<div>
<LoginComponent ifShow={this.state.ifLoginShow}/>
<RegisterComponent ifShow={this.state.ifRegisterShow}/>
</div>
)
}
}
答案 1 :(得分:1)
好的,这有效......
export default {
path: '/',
component: App,
indexRoute: { component: Child },
childRoutes: [ //<- ***REGULAR ROUTES ARE CHILDREN HERE***
{ path: 'test1', component: Child1 },
{ path: 'test2', component: Child2 },
{ component: AuthHandler,
childRoutes: [ //<- ***AUTH ROUTES ARE CHILDREN HERE***
{path: 'test3', component: Child3},
{path: 'test4', component: Child4}
]
}
]
};
...转到/ test1或/ test2是不安全的路由(任何测试和直接的孩子都和/本身一样)。但是,AuthHandler子项下的任何子项(除非您真的需要路径,否则没有或需要路径)将首先通过AuthHandler - 您可以在其中执行任何操作。因此/ test3和/ test4是安全路由(假设您以首选方式在AuthHandler中处理auth)。这也适用于JSX语法路由,只要它们嵌套相同即可。