web123456

React Router 5.1.0 uses useHistory for page redirect navigation

Starting from React Router v5.1.0, a new useHistory hook (hook) has been added. If you are using React >16.8.0, write the following function components and use useHistory to implement page jump navigation during programming.

Example:

import { useHistory } from "react-router-dom";
function HomeButton() {
  const history = useHistory();
  function handleClick() {
    ("/home");
  }
  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

 

React Router v4 programming page jump method (supplement)

If it is React Router v4, you can use the following method:

  • Using the withRouter component
  • Use the <Route> tag
  • Using context

1. Use the withRouter component

The withRouter component will inject history object as the property of that component. In this way, there is no need to deal with context, and you can directly access push and replace methods.

Example:

import { withRouter } from 'react-router-dom'
const Button = withRouter(({ history }) => (
  <button
    type='button'
    onClick={() => { ('/new-location') }}
  >
    Click Me!
  </button>
))

2. Use the <Route> tag

The <Route> component is not only used to match positions. You can render a pathless route that always matches the current location. The <Route> component passes the same attribute as withRouter, so it can access the history method through the history attribute.

import { Route } from 'react-router-dom'
const Button = () => (
  <Route render={({ history}) => (
    <button
      type='button'
      onClick={() => { ('/new-location') }}
    >
      Click Me!
    </button>
  )} />
)

3. Use context

This method is not recommended, the context API is not very stable. Examples are as follows:

const Button = (props, context) => (
  <button
    type='button'
    onClick={() => {
      ('/new-location')
    }}
  >
    Click Me!
  </button>
)

 = {
  history: ({
    push: 
  })
}

Recommended methods 1 and 2, which are easy to implement.