我正在使用HOC组件来限制对未登录用户的路由访问。这个HOC重新挂载子组件时挂载或重新呈现时,直接从url访问此路线(在应用程序第一次加载时)的问题。例如,我在PaperWorkProgress
组件中有3次did mount
。路由授权HOC导致重新安装儿童3次
路由定义:
<Route path="/paperwork/progress" component={RequireAuth(PaperWorkProgress)}/>
这里HOC代码:
import React, {Component} from 'react';
import {connect} from 'react-redux';
export default function(ComposedComponent) {
class Authentication extends Component {
// check if token exists in storage
componentWillMount() {
const token = localStorage.getItem('token');
if (!token) {
const {pathname, search} = this.props.location;
this.props.history.push({
pathname: '/signin',
search: `?redirect_to=${pathname}${search}`,
});
}
}
// additional check
componentWillUpdate(nextProps) {
if (!nextProps.loggedIn) {
const {pathname, search} = this.props.location;
this.props.history.push({
pathname: '/signin',
search: `?redirect_to=${pathname}${search}`,
});
}
}
render() {
return <ComposedComponent {...this.props} />;
}
}
function mapStateToProps(state) {
return {loggedIn: state.session.loggedIn};
}
return connect(mapStateToProps)(Authentication);
}
任何想法?
尝试把它'componentDidMount' – Dane
我在细节上如何一个auth HOC可以用在刀刃上解释这里:https://stackoverflow.com/questions/46379934/react-router-v4-authorized-routes-and-components –
@MatthewBarbara我的HOC基于你的解决方案,但没有上下文功能。 – Kort