JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

History Object in React Router

Author:JIYIK Last Updated:2025/03/03 Views:

Navigation is an important part of any modern application. JavaScript-based frameworks often rely on a default history object as the basis for their different navigation solutions. This object is available as a property of the DOM's Window object.

When developing applications in React, developers can use the React Router library. It provides all navigation features, including 历史包an improved version of the browser history interface. The React Router historyobject includes many properties and methods that we can use to configure navigation, such as action, location, , .push()or .replace(). We will review how to best use these properties and methods to handle key navigation needs in the following sections.

The history package (or simply history history) is the key tool you need to manage session history in JS. As mentioned before, it includes many methods, all of which are useful in their own way. Nonetheless, history.push()methods are arguably the most important and will be the main focus of our guide.

The browser keeps track of the different URLs that a user visits. This session history is called the history stack, and it is required for the browser's back or forward buttons to work.

The History object has properties and methods that can affect the history stack. For example, .replace()the method replaces the most recent path on the history stack. .lengthThe property gives us the number of entries in the stack.

.push()The method is probably the most important and widely used method. Developers use it to push entries into the stack, redirecting the user to another page. This method is essential and we will discuss it in detail later in this guide.

The location object shows information about the current (and sometimes past) pathname of your application. React Router makes this object available in many ways. For example, it can be accessed in a component as propsa property of the location object . Learn more on the Routeofficial React Router documentation .

historyObjects also have locationproperties. However, historyobjects are mutable, so using locationthe value of a property is not recommended. Instead, you can <Route>access it through the props of location. This way, you can be sure you are accessing the correct 位置information.

When developing applications, you often need to change the user's path after the user performs an action. To do this, you need to set up an event handler and use .push()the method to redirect to a specific path name.

Functional components have become more useful since the introduction of hooks. With the release of v5, react-router-doma hook is also provided useHistory()to make it easier to access the history object. Let's look at a practical example:

import { useHistory } from "react-router-dom";
function Homepage() {
  let historyObj = useHistory();
  function handleClick() {
    historyObj.push("/");
  }
  return (
    <div>
    ...
    <button onClick={() => handleClick()}>
      Go to Homepage
    </button>
    ...
    </div>
  );
}

In this example, we have a simple HomepageComponent. First, we react-router-domimport hooks from the Components package useHistory. You must have react-router-domversion 5 (or higher) installed for this to work properly. Hooks returns the Component's historyComponent object, stored in historyObjthe Components variable.

We can use the previously mentioned method in the handler function .push(string), which accepts a string parameter. It pushes the string onto the history stack and takes the user to the specified path.

Version 4 of React Router does not include useHistorythe hook, so you have to propspass historythe object via . This is also the only way to access class components which is not compatible with hooks 历史.

You can navigate to another path using the method in a handler function .push(). Let's look at this example:

function handleClick() {
    this.props.history.push("/")
}

To access the object via props history, you have to make sure your component has access to it. There are two ways to do this.

<Route path="/" component={Homepage} />

In this case, Homepagethe component will have access to historythe object via props.

<Route path="/" render={(props) => <Homepage {...props} />}/>

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

React Tutorial - Transferring Props

Publish Date:2025/03/16 Views:188 Category:React

React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.

React Tutorial: Props Anti-Pattern

Publish Date:2025/03/16 Views:187 Category:React

React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.

React Tutorial - Props Validation

Publish Date:2025/03/16 Views:102 Category:React

Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.

Why do you need to bind event handlers in React Class Components?

Publish Date:2025/03/16 Views:60 Category:React

When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:

Solution to the error "does not contain a default export" in React

Publish Date:2025/03/16 Views:191 Category:React

When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.

Solve the Module not found: Can't resolve 'react-bootstrap' error

Publish Date:2025/03/16 Views:90 Category:React

To resolve the error "Module not found: Error: Can't resolve 'react-bootstrap'", make sure to install the react-bootstrap package by opening a terminal in the root directory of the project and running the command `npm install react-bootstrap bootstrap

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial