简体   繁体   中英

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

I have made some state in reducers which return a value of logged_in which 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 everytime this page is visit, it will check if the logged_in state is true or false . if it false user will be redirect to /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

Anyone has the same problem? thanks in advance

Make sure to add the history 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 react-router 2

In react-router 2.0, you would add the router context instead :

static contextTypes = {
  router: PropTypes.object
}

And then you can do this:

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

I believe you want to use pushState(null, '/login') instead of transitionTo. Also I would recommend making a Higher Order Component that does this type of authorization for you so you don't have to write that componentDidMount logic every time.

Here is an example of the Higher Order Authorization Component I am talking about: https://github.com/SpencerCDixon/Kira/blob/master/client/config/routes.js#L29-L60

EDIT I just realized you arn't using redux-router. But I would recommend either using redux-router or redux-simple-router in combination with react router

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM