我正在使用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