background

Sometimes, we need to jump to a route in a non-component environment, usually we use history.push() but because history is usually obtained by useHistory, and non-components can’t be retrieved in this way, how do we get it?

Methods a

Use the location.href= path method

Jumping this way does the trick, but it forces a page refresh, which is the opposite of the goal of our single-page application

Method 2 (Recommended)

React-router-dom contains the router package, but the router does not have a history attribute

The formula is as follows:

Router + HashHistroy = HashRouter

Router + BrowerHistroy = BrowerRouter

Making: reference

When you install react-router-dom, the history package is installed by default, and you can use this package to create your own history objects

Implementation approach

Import the Router separately and create your own history

The implementation code

import { Router, Route, Switch, Redirect } from 'react-router-dom'
​
import { createBrowserHistory } from 'history'
export const history = createBrowserHistory()
function App () {
  return (
    <Router history={history}>
Copy the code

In order to retrieve routing information in a non-component environment, we need to customize the Router’s history

steps

  1. Create the history.js file
  2. In this file, create a Hisotry object and export it
  3. Import the history object in the file that uses routing and set it to the history of the Router

The core code

Improved: Encapsulate the history method separately.

Utils/history. In js:

Import {createBrowserHistory} from 'history' const history = createBrowserHistory() export default historyCopy the code

This allows us to jump using History in a non-component environment

App. In js:

/ / note: Here, Import {Router} from 'react-router-dom' import history from '@/utils/history' function App() {return ()  <Router history={history}></Router> ) }Copy the code