本文介绍了React从react-router路由上做登陆验证控制的方法,分享给大家,具体如下:
验证代码
function requireAuthentication(Component) {
// 组件有已登陆的模块 直接返回 (防止从新渲染)
if (Component.AuthenticatedComponent) {
return Component.AuthenticatedComponent
}
// 创建验证组件
class AuthenticatedComponent extends React.Component {
static contextTypes = {
router: React.PropTypes.object.isrequired,}
state = {
login: true,}
componentwillMount() {
this.checkAuth();
}
componentwillReceiveProps(nextProps) {
this.checkAuth();
}
checkAuth() {
// 判断登陆
const token = this.props.token;
const login = token ? token.login : null;
// 未登陆重定向到登陆页面
if (!login) {
let redirect = this.props.location.pathname + this.props.location.search;
this.context.router.push('/login?message=401&redirect_uri=' + encodeURIComponent(redirect));
return;
}
this.setState({login});
}
render() {
if (this.state.login) {
return <Component {...this.props}/>
}
return ''
}
}
// 不使用 react-redux 的话直接返回
// Component.AuthenticatedComponent = AuthenticatedComponent
// return Component.AuthenticatedComponent
function mapStatetoProps(state) {
return {
token: state.token,};
}
function mapdispatchToProps(dispatch) {
return {};
}
Component.AuthenticatedComponent = connect(mapStatetoProps,mapdispatchToProps)(AuthenticatedComponent);
return Component.AuthenticatedComponent
}
路由上使用
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。