Obtain routing information in a non-component environment

Direct assignment with location.href causes a page refresh.

Scenario: A responder interceptor is used to uniformly process the forward after token expiration. UseHistory cannot be directly used in the responder interceptor

background

The react-router-dom contains the router package directly, but the router does not have the history attribute

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

How do I use a history jump in a non-component?

Train of thought

Import the Router separately and create your own history,

We need to customize the history of the Router

steps

  1. Create the utils/history.js file

  1. In this file, create a Hisotry object and export it

3. Import the history object in app. js

In this case, the HashRouter and BrowerRouter do not need to be written

4. Set this parameter to Router history

The core code

Wrap the history method separately.

Utils /history.js: same as above, can be copied directly

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

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