React-router-component 的官方 github 页面中提到如下:
例如,您可以为匿名用户和登录用户返回一组不同的允许位置。
这正是我想要实现的目标,但我实际上无法在任何地方找到如何做到这一点的教程。
所以基本上我想为登录用户和访客用户设置单独的路由器。访客路由器默认为登录页面,可能会重定向到登录错误页面或关于页面。当用户成功登录后,登录的路由器将获得控制权并默认进入系统概览页面。登录的路线还应该将导航面板呈现到每个页面。
React-router-component 的官方 github 页面中提到如下:
例如,您可以为匿名用户和登录用户返回一组不同的允许位置。
这正是我想要实现的目标,但我实际上无法在任何地方找到如何做到这一点的教程。
所以基本上我想为登录用户和访客用户设置单独的路由器。访客路由器默认为登录页面,可能会重定向到登录错误页面或关于页面。当用户成功登录后,登录的路由器将获得控制权并默认进入系统概览页面。登录的路线还应该将导航面板呈现到每个页面。
用户登录/注册后,您可以更改this.setState({isLoggedIn: true}
父组件( index.js 或 App.js )中的状态(例如)。现在根据状态,您可以将用户重定向到所需的位置。
<Route path='/dashboard'
render={() =>
this.state.isLoggedIn ?
<Dashboard user={this.state.user} /> :
<Redirect to="/home"/>
}
/>
您可以在此处查看完整代码:链接。如果有任何疑问,请在评论部分提问。
您可以做的就是将您的路线包装在所谓的组合组件中。它将检查您的用户是否经过身份验证,如果他/她没有,它会将他们踢回您选择的任何路线。
这是一个组合组件的示例,然后我将向您展示如何在您的路由文件中使用它。
import React, {Component} from 'react';
import {connect} from 'react-redux';
export default function(ComposedComponent) { //This code right here serves as the base for any high order component
class Authentication extends Component {
static contextTypes = { //static creates a class level object that will give any other method in this component access to Authentication.contextTypes
router: React.PropTypes.object //This lets react know ahead of time we will use the router and it defines its type as object
}
componentWillMount() {
if (!this.props.authenticated) {
this.context.router.push('/signup');
}
}
componentWillUpdate(nextProps) {
//this lifecycle method runs when the component is about to update with new props, nextProps are those new properties for the rerender
if (!nextProps.authenticated) {
this.context.router.push('/signup');
}
}
//{...this.props} makes sure the new combined component Enhanced Component will have all the props of the original component passed into this function/Authentication class
//it maintains those props even though it's combining two components together to form a Enhanced Component
render() {
return (
<ComposedComponent {...this.props} />
);
}
}
function mapStateToProps(state) {
return { authenticated: state.user.authenticated };
}
return connect(mapStateToProps)(Authentication);
}
我已在路由文件中将上面的身份验证组件作为 RequireAuth 导入。它将检查用户是否在我的 redux 状态下进行了身份验证。如果用户未通过身份验证,则用户将被踢回我的“/注册”路线。您可以看到在身份验证的生命周期方法中发生的位置。基本上,如果我使用 RequireAuth 在我的路由中包装任何组件,这些组件将继承其生命周期方法。您可以使用它来检查他们是否已登录。您可以让某些用户具有管理员权限等。您只需在生命周期方法中检查用户的资格并将路由推送到您想要的任何地方。
export default (
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="inventory" component={RequireAuth(Inventory)} />
<Route path="signup" component={Signup} />
<Route path="single-product/:id" component={RequireAuth(Product)} />
<Route path="examples" component={Examples} />
<Route path="pricing" component={Pricing} />
<Route path="profile" component={RequireAuth(Profile)} />
<Route path="allProducts" component={RequireAuth(AllProducts)} />
<Route path="reporting" component={RequireAuth(ReportingContainer)} />
<Route path="signout" component={Signout} />
</Route>
);