React redux how to redirect to a specific page using a react router

I made some state in reducers that return a logged_in value that has a boolean value.

Here is my code:

 import React from 'react' import { render } from 'react-dom' import { Router, Route, Link } from 'react-router' import { connect } from 'react-redux' export class NewStock extends React.Component { componentWillMount() { const { router, session } = this.props; if (session.userSessionData.get('logged_in') == false) { router.transitionTo('/login'); } }; render() { const { router, session } = this.props const currentRoute = router.location.pathname return ( <div className="row"> <h1>Hello World</h1> </div> ) } } function select(state) { return { router: state.router, flash: state.flash.get('newStock'), newStock: state.newStock, session: state.session } } export default connect(select)(NewStock) 

This component is on the /new path

I want to check every time this page visits, it checks if logged_in true or false . if the user false is redirected to the /login page.

  componentWillMount() { const { router, session } = this.props; if (session.userSessionData.get('logged_in') == false) { router.transitionTo('/login'); } }; 

But it returns an error that says:

Uncaught TypeError: router.transitionTo is not a function

Does anyone have the same problem? thank you in advance

+3
source share
2 answers

Be sure to add a story context to your component:

 static contextTypes = { location: PropTypes.object, history: PropTypes.object } 

Then you can do this:

 componentWillMount() { const { session } = this.props; if (!session.userSessionData.get('logged_in')) { this.context.history.pushState(null, '/login'); } }; 

Update for Jet Router 2

In response-router 2.0, you would instead add a router context :

 static contextTypes = { router: PropTypes.object } 

And then you can do it:

 componentWillMount() { const { session } = this.props; if (!session.userSessionData.get('logged_in')) { this.context.router.push({ pathname: '/login' }); } }; 
0
source

I believe you want to use pushState(null, '/login') instead of going. I would also recommend creating a higher-order component that does this type of authorization for you, so you don't need to write this componentDidMount logic every time.

Here is an example of a higher order authorization component that I'm talking about: https://github.com/SpencerCDixon/Kira/blob/master/client/config/routes.js#L29-L60

EDIT I ​​realized that you are not using a reduction router. But I would recommend either using a reduction router or a reduction simple router in combination with a react router

0
source

All Articles