React Router cannot get / depends on onEnter function

I'm new to React and hope someone can shed some light on why this is happening and how to debug it.

I have defined the following routes:

export default (withHistory, onUpdate) => { const history = withHistory? (Modernizr.history ? new BrowserHistory : new HashHistory) : null; return ( <Router history={history}> <Route path='/login' component={Login} /> <Route path='/' component={Home} onEnter={requireAuth} /> </Router> ); }; 

requireAuth should check if the user is registered and redirect him to the login page if not:

 function requireAuth(nextState, transition) { transition.to("/login"); } 

If I leave the call to transtion.to and go to the root URL, I just see a message saying "Can not Get /" without error messages in the debugger. Finding a breakpoint on this line does nothing.

Which is especially strange if I replaced transition.to(...) with a debugger; statement debugger; , then the method is called, and routing works fine.

I should have some misunderstanding, some ideas about what it is?

Edit: I have to add that switching to host:port/login works fine, so I know that the login route works.

+7
javascript url-routing reactjs
source share
2 answers

Based on the Angular background, I incorrectly assumed that routing occurs entirely on the client side. It is possible to use a responder adapter for routing on the client side and on the server side.

The transition.to call worked fine on the client side, but threw an exception when the initial server-side routing came in and returned the Cannot GET / page. An exception was found but nothing was recorded.

I added an if statement to make sure we were working on the client:

 if(window.location) { if(!loggedIn) { transition.to("/login"); } } 

There is probably a better way to handle this, and if I find out, in the end I will update my answer.

+2
source share

According to current documents, the onEnter hook receives the replace function as the second parameter. i.e.

 type EnterHook = (nextState: RouterState, replace: RedirectFunction, callback?: Function) => any; 

Are you using a different version of the jet router? I tried to look at alternative docs for the onEnter hook, which takes a transition object as its second parameter, but I was not very lucky to find anything.

0
source share

All Articles