How to redirect to a specific page according to a

2019-05-30 06:07发布

How to redirect to a specific page according to a condition in "react-router": "^4.0.0".

var { HashRouter, Route, Switch} = require('react-router-dom');
var {Provider}  = require('react-redux');
    firebase.auth().onAuthStateChanged((user) => {
      if (user){
        this.props.history.push('/todos/');
      }else{
        this.props.history.push('/');
      }
    });


    store.dispatch(actions.startAddTodos());

    ReactDOM.render(
      <Provider store = {store}>
        <div>
          <HashRouter>
            <div>
              <div className="columns medium-6 large-4 small-centered">
                <Switch>
                  <Route path='/todos' component={TodoApp}/>
                  <Route path='/login' component={Login}/>
                  <Route component={Login}/>
                </Switch>
              </div>
            </div>
          </HashRouter>
        </div>
      </Provider>,
      document.getElementById('app')
    );

Cannot read property 'props' of undefined


EDIT :

The Application on Github: React-Todo

2条回答
别忘想泡老子
2楼-- · 2019-05-30 06:42

You can't use this.props because you are not inside of a component.

So to perform redirect you need to use the Redirect component from react-router-dom

I would recommend you create an HOC(High order component to take care of it.

import React from 'react'
import { Redirect, Route } from 'react-router-dom'
import firebase from 'firebase'

const PrivateRoute = ({ component: Component, ...rest }) => {
  return(
    <Route {...rest} render={props => (
      firebase.auth().onAuthStateChanged((user) => user
        ?(
          <Component />
        ) 
        :(
          <Redirect to={{
            pathname: '/login',
            state: { from: props.location }
          }}/>
        ) 
      )
 
      
    )}/>
  )
}

export default PrivateRoute

Then you only need to import PrivateRoute inside of your index.js file instead of using Route use PrivateRoute for the routes that require being authenticated.

var { HashRouter, Route, Switch} = require('react-router-dom');
var PrivateRoute = require('./privateRoute')
var { Provider }  = require('react-redux');

    store.dispatch(actions.startAddTodos());

    ReactDOM.render(
      <Provider store = {store}>
        <div>
          <HashRouter>
            <div>
              <div className="columns medium-6 large-4 small-centered">
                <Switch>
                  <PrivateRoute path='/todos' component={TodoApp}/>
                  <Route path='/login' component={Login}/>
                  <Route component={Login}/>
                </Switch>
              </div>
            </div>
          </HashRouter>
        </div>
      </Provider>,
      document.getElementById('app')
    );

查看更多
太酷不给撩
3楼-- · 2019-05-30 07:02

If you're using react router then it can be easier if you're maintaining user auth in your state.

  { /* Protect your routes you can include any no.of routes */ }
  <Route onEnter={requireLogin}>
    <Route path='/todos' component={TodoApp}/>
  </Route>

Next, write a small wrapper for requireLogin in which you check the auth state and do redirection inside it. It looks something like this

const requireLogin = (nextState, replace, cb) => {
            function checkAuth() {
             const user = firebase.auth().onAuthStateChanged(user => user); // check login in your state
              if (!user) {
                replace('/'); // make user to redirect to some route based on your requirement
              }
              cb(); //if user present in it fallback to here
            }
    };
查看更多
登录 后发表回答