Forwarding redirection to answer router 2.4.0?

I am currently using "react-router": "^2.4.0" in my chat application and am confused how to redirect when there is no user. I don't think redirection works in "^2.4.0" .

Should I use onEnter hooks in my chat ?

Something like that:

  <Route path="chat" component={Chat} onEnter={Chat.willTransitionTo}/> 

routes.js

  <Route path="/" component={App} > <IndexRoute component={Chat} /> <Route path="chat" component={Chat} /> <Route path="login" component={Login} /> </Route> 

Chat.jsx

 static willTransitionTo(transition){ var state = ChatStore.getState(); if(!state.user){ transition.redirect('/login'); } } 
+5
source share
2 answers

I did this using setRouteLeaveHook , as it says here: https://github.com/ReactTraining/react-router/blob/master/docs/guides/ConfirmingNavigation.md

return false to prevent transition without user request

However, they forget to mention that the hook must also be unregistered, see here and here .

We can use this to implement our own solution as follows:

 class YourComponent extends Component { constructor() { super(); const {route} = this.props; const {router} = this.context; this.unregisterLeaveHook = router.setRouteLeaveHook( route, this.routerWillLeave.bind(this) ); } componentWillUnmount() { this.unregisterLeaveHook(); } routerWillLeave() { // return false to prevent a transition w/o prompting the user, // or return a string to allow the user to decide: if (!this.state.isSaved) { return 'Your work is not saved! Are you sure you want to leave?' } } ... } YourComponent.contextTypes = { router: routerShape }; 
+1
source

There is at least a spelling mistake:

 tansition.redirect('/login'); 

Must be:

 transition.redirect('/login'); 

You should also check the example of interaction with the router: https://github.com/reactjs/react-router/tree/master/examples/auth-flow

+1
source

All Articles