为了帮助回答您的问题,我想您可能还需要询问该路线应 如何
被封锁。通过上面的示例,您还没有一种机制可以帮助回答“我是否可以访问此页面”问题。这可能来自
state,redux或其他确定用户是否已登录的方法。
由于
react-router只是普通的React(我最喜欢的部分之一!),所以您拥有所有可用的工具,可以有条件地显示React应用程序的 任何
部分。
这是几个示例,说明如何实现此目标(绝不是穷举。要有创造力!这完全取决于您的要求和所使用的工具)
class AllRoutes extends Component{ render(){ return( <Switch> <Route exact path="/login" component={Login} /> <Route exact path="/signup" component={SignUp} /> { this.state.authenticated &&<Route exact path="/Welcome" component={Welcome} /> } </Switch> ); }}我最喜欢的方法之一就是创建一个
ProtectedRoute组件
class ProtectedRoute extends Component { render() { const { component: Component, ...props } = this.props return ( <Route {...props} render={props => ( this.state.authenticated ? <Component {...props} /> : <Redirect to='/login' /> )} /> ) }}class AllRoutes extends Component { render() { return ( <Switch> <Route path='/login' component={Login} /> <ProtectedRoute path='/welcome' component={Welcome} /> </Switch> ) }}尽管我没有包括如何
state.authenticated设置的任何特定逻辑,但这可能来自任何地方(决不是来自
state)。尽最大努力回答“如何确定用户是否已通过身份验证”的问题,并将该机制用作处理路由身份验证的手段。



