它无限变化,因为onChange
调用replace
尝试
onChange: function(prevState, {location:{pathname:next}}, replace)=> {
if(!logined && next !== '/login') {
replace('/login');
}
}
还可以在一个地方处理身份验证,您可以使用 HOC,类似的东西
const CheckAuth = (isLogined, redirectPath) => Component =>
class CheckAuth extends React.Component {
componentWillUpdate(nextProps, nextState){
//Check auth on change
this.checkAuth(nextProps);
}
componentWillMount(){
//Check auth on enter
this.checkAuth(this.props);
}
checkAuth({location}){
if(!isLogined && location.pathname!==redirectPath) {
browserHistory.replace(redirectPath);
}
}
render(){
return (<Component {...this.props}/>);
}
};
和 App 组件
class App extends React.Component { ... }
export default CheckAuth(isLogined,'/login')(App);
此外,还有一种使用redux-auth-wrapper的方法