how to redirect on ponentWillMount using react-router
export class NewStock extends React.Component {
constructor(props, context) {
super(props, context);
}
ponentWillMount() {
const { session, dispatch, router } = this.props
if (session.userSessionData.get('logged_in') == false) {
router.transitionTo('/login')
}
};
this code:
router.transitionTo('/login')
only return:
Uncaught TypeError: router.transitionTo is not a function
how to redirect on ponentWillMount using react-router
export class NewStock extends React.Component {
constructor(props, context) {
super(props, context);
}
ponentWillMount() {
const { session, dispatch, router } = this.props
if (session.userSessionData.get('logged_in') == false) {
router.transitionTo('/login')
}
};
this code:
router.transitionTo('/login')
only return:
Uncaught TypeError: router.transitionTo is not a function
Share
Improve this question
edited Jun 18, 2018 at 13:40
Hinrich
14k8 gold badges48 silver badges67 bronze badges
asked Dec 15, 2015 at 8:57
Kris MPKris MP
2,4157 gold badges28 silver badges38 bronze badges
2
-
I only saw examples where the transitionTo() was used from the Router.Navigation mixin. You need to add that mixin, and then you'll be able to say
this.transitionTo(...)
– Johnny Commented Jan 12, 2016 at 20:29 - One more thing, probably it's better to transition programatically on a willTransitionTo static callback. This will prevent your view being visible for a short while before your transitionTo() is called. – Johnny Commented Jan 12, 2016 at 21:16
2 Answers
Reset to default 12Try this.props.history
:
const { history } = this.props
history.pushState(null, '/login') or
history.replaceState(null, '/login')
If your module isn't a direct descendant of the router you can still access this prop by wrapping your ponent in the withRouter(YourComponent)
HOC (in v4).
What I'm doing is using the onEnter
prop of a route. This allows me to centralize my authentication better. I got my inspiration from the react-router examples
I came here because I was fumbling about with the same aproach as you, but got into an huge mess of unmanageable code VERY SOON.
Hope that for all ing here, you will learn from my mistake.
function requireAuth(nextState, replace) {
if (!UserStore.userIsSignedIn()) {
replace({
pathname: '/login',
state: {nextPathname: nextState.location.pathname}
})
}
}
render((
<Router history={hashHistory}>
<Route path="/" ponent={PageHeader}>
<IndexRoute ponent={AssignmentOverview} onEnter={requireAuth}/>
<Route path="login" ponent={UserLoginForm}/>
<Route path="logout" ponent={UserLogout}/>
<Route path="profile" ponent={UserProfile} onEnter={requireAuth}/>
<Route path="assignmentform" ponent={AssignmentForm} onEnter={requireAuth}/>
</Route>
</Router>
), document.getElementById('content'));