2

It seems if I change path in root onEnter or onChange hook, the url will change infinite. But if I change path in child routes, it will work. Actually I want to handle the authentication in one place, otherwise every child route should handle the same logic.

{
    path: '/',
    onChange: function(prevState, nextState, replace, callback) { 
        if(!logined) {
            replace('login');
        }
    },
    childRoutes: [
        ....
    ]
}
jason
  • 1,621
  • 6
  • 21
  • 39

1 Answers1

0

It changes infinitly because onChange invokes on replace

try

 onChange: function(prevState, {location:{pathname:next}}, replace)=> {
      if(!logined && next !== '/login') {
          replace('/login');
      }
 }

also to handle the authentication in one place, you can use HOC, something like that

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}/>);
    }
};

and App component

class App extends React.Component { ... }
export default CheckAuth(isLogined,'/login')(App);

also, there is a way with redux-auth-wrapper

Kokovin Vladislav
  • 10,241
  • 5
  • 38
  • 36