React-Router is the routing solution in React scenarios

Routers: BrowserRouter and HashRouter Routers are responsible for sensing and responding to routing changes. They are the most important link in the entire routing system. The React-Router allows us to use hash (for HashRouter) and Browser (for BrowserRouter) routing rules

The two use the same method, the difference is the instantiation method of the underlying call:

HashRouter calls createHashHistory, BrowserRouter calls createBrowserHistory

  • CreateBrowserHistory: It will use the HTML5 History API in the browser to handle urls that look like this: example.com/some/path. As a result, BrowserRouter uses HTML 5’s History API to control route jumps
  • CreateHashHistory: This is a method that uses hash tag (#) to handle urls like example.com/#/some/path.

Implementation principle:

  • The HashRouter listens for changes to the hash using hashChange time and modiates the hash using window.location.hash
  • HistoryRouter: HTML4 provides us with history capabilities
window.history.forward()  // Proceed to the next page
window.history.back() // Go back to the previous page
window.history.go(2) // Proceed two pages
window.history.go(-2) // Go back two pages
Copy the code

Starting with HTML5, two new apis are available

history.pushState(data[,title][,url]); // Appends a record to the browsing history
history.replaceState(data[,title][,url]); // Modify (replace) the current page in the browsing history
Copy the code

In history mode, we can do this by listening for popState events:

window.addEventListener('popstate'.function(e) {
  console.log(e)
});

Copy the code

The PopState event is emitted whenever the browsing history changes.

Calls to methods like go, Forward, and back do trigger popState, but pushState and replaceState do not. However, this is not a problem, we can manually trigger events through custom events and the global event bus