In React project
- useNavigate
- useHistory
- window
useNavigate
Introduced in React Router v6,useNavigate
is a hook specifically used to navigate between different routes.
It returns a function (navigate
), used to programmatically navigate to different routes.
Example usage:
import { useNavigate } from 'react-router-dom'; function MyComponent() { const navigate = useNavigate(); const handleButtonClick = () => { // Navigate to /other-route when button clicks navigate('/other-route'); }; return ( <button onClick={handleButtonClick}>Click to navigate to another route</button> ); }
useHistory
useHistory
It was introduced in React Router v5 to access routing history objects.
Returns an object containing information about navigation history, includingpush
andreplace
Method, used to navigate to different routes.
Example usage:
import { useHistory } from 'react-router-dom'; function MyComponent() { const history = useHistory(); const handleButtonClick = () => { // Navigate to /other-route as push when button clicks ('/other-route'); }; return ( <button onClick={handleButtonClick}>Click to push Navigate to other routes</button> ); }
window
window
The object is a global object in JavaScript, representing the browser window. If you need to use it directlywindow
The object performs some global related processing, such as opening a new browser window, modifying the browser address bar, etc., which can be done. Here is a simple example:
import React from 'react'; function MyComponent() { const handleOpenNewWindow = () => { // Open a new browser window ('/new-page', '_blank'); }; const handleModifyLocation = () => { // Modify the browser address bar = '/modified-page'; }; return ( <div> <button onClick={handleOpenNewWindow}>Open a page in a new window</button> <button onClick={handleModifyLocation}>Modify the browser address bar</button> </div> ); } export default MyComponent;
Summarize
In React, it is usually recommended to use itreact-router-dom
Provided navigation tools such asuseNavigate
oruseHistory
, without relying directly onwindow
Objects to handle navigation. This is becausereact-router-dom
Provides abstractions that are more in line with React architecture and routing libraries, and can work better with React components.
useNavigate
Focus more on providing navigation functions, anduseHistory
This provides more information about navigation history and can also be used for navigation. In React Router v6, it is recommended to use ituseNavigate
Navigate.
usewindow
The object performs some global related processing, such as opening a new browser window and modifying the browser address bar
This is the article about the detailed explanation of the three common routing processing methods in React. For more related React routing processing content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!