What is the best way to redirect a page using React Router?

后端 未结 5 629
刺人心
刺人心 2020-11-28 20:43

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

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

    import          
    
    
            
5条回答
  •  鱼传尺愫
    2020-11-28 21:14

    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 and can implement the following logic:

    import React from 'react'
    import  { Redirect } from 'react-router-dom'
    
    const ProtectedComponent = () => {
      if (authFails)
        return 
      }
      return 
    My Protected Component
    }

    Keep in mind that if you want 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 for withRouter.

    If your component is a child of a component, i.e. if it is something like , you don't have to wrap your component with withRouter, because 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 an onClick event:

    some stuff

    or you can use a component:

      some stuff 
    

    I think the rule of thumb with this case is to try to use first, I suppose especially because of performance.

提交回复
热议问题