What is the best way to redirect a page using Reac

2019-01-30 18:31发布

问题:

I am new to React Router and learn that there are so many ways to redirect a page:

  1. Using browserHistory.push("/path")

    import { browserHistory } from 'react-router';
    //do something...
    browserHistory.push("/path");
    
  2. Using this.context.router.push("/path")

    class Foo extends React.Component {
        constructor(props, context) {
            super(props, context);
            //do something...
        }
        redirect() {
            this.context.router.push("/path")
        }
    }
    
    Foo.contextTypes = {
        router: React.PropTypes.object
    }
    
  3. In React Router v4, there's this.context.history.push("/path") and this.props.history.push("/path"). Details: How to push to History in React Router v4?

I'm so confused by all these options, is there a best way to redirect a page?

回答1:

Actually it depends on your use case

1) You want to protect your route from unauthorized users

If that is the case you can use the component called <Redirect /> and can implement the following logic:

import React from 'react'
import  { Redirect } from 'react-router-dom'

const ProtectedComponent = () => {
 if (authFails)
    return <Redirect to='/login'  />
}
return <div> My Protected Component </div>
}

But keep in mind that, if you want <Redirect /> to work the way you expect, you should place it inside of your component's render method so that it should eventually be considered as a DOM element, otherwise it won't work.

2) You want to redirect after a certain action (let's say after creating an item)

In that case you can use history

myFunction() {
 addSomeStuff(data).then(() => {
      this.props.history.push('/path')
    }).catch((error) => {
      console.log(error)
    })

or

myFunction() {
 addSomeStuff()
 this.props.history.push('/path')
}

In order to have access to history, you can wrap your component with an HOC called withRouter when you wrap your component with it, it passes match location and history props. For more detail please have a look at the official documentation about withRouter

If your component is a child of <Route /> component, I mean if it is something like <Route path='/path' component={myComponent} /> you don't have to wrap your component with withRouter <Route /> passes match location and history to its child.

3) Redirect after clicking some element

There are two options here. You can use history.push() by passing it to a onClick event

<div onClick={this.props.history.push('/path')}> some stuff </div>

or you can use <Link /> component

 `<Link to='/path' > some stuff </Link>`

I think rule of thumb with this case is (I suppose especially beceause of performance) try to use <Link /> first